using System; using System.Collections.Generic; using System.Linq; namespace _15._3Sum; public class Solution { class SequenceComparer:IEqualityComparer> { public bool Equals(IEnumerable seq1,IEnumerable seq2) { return seq1.SequenceEqual(seq2); } public int GetHashCode(IEnumerable seq) { int hash = 1234567; foreach(T elem in seq) hash = unchecked(hash * 37 + elem.GetHashCode()); return hash; } } public IList> ThreeSum(int[] nums) { Dictionary dict = new Dictionary(); foreach (var num in nums) { if (dict.ContainsKey(num)) dict[num]++; else dict.Add(num, 1); } HashSet> answer = new HashSet>(new SequenceComparer()); int[] keys = dict.Keys.ToArray(); for (int i = 0; i < keys.Length; i++) { int countI = dict[keys[i]]-1; for (int j = i; j < keys.Length; j++) { int countJ = j == i ? (countI-1) : (dict[keys[j]]-1); int v1 = keys[i]; int v2 = keys[j]; int v3 = -(v1+v2); if (v3 == v1) countI--; if (v3 == v2) countJ--; bool can = dict.ContainsKey(v3); if (can && countI >= 0 && countJ >= 0) { var list = new List() { v1, v2, v3 }; list.Sort(); answer.Add(list); } countI = dict[keys[i]]-1; } } return answer.ToList(); } }