Hashset<T>.Add(..)
wont add any duplicates items anyway it's checking thethat internally but we still need to know if the item is actually duplicate to see if we need to add it to the results
I prefer not checking if the key is contained but rather check the length before adding the item and after adding the item. If they are different that means there is no such item inuse the returned boolean value from HashSetHashSet<T>.Add()
.
public static IList<IList<int>> ThreeSum(int[] nums)
{
IList<IList<int>> results = new List<IList<int>>();
HashSet<Triplet> keys = new HashSet<Triplet>();
if (nums == null || nums.Length == 0)
return results;
Array.Sort(nums);
int length = nums.Length;
int target = 0;
for (int i = 0; i < length - 2; i++)
{
int firstNo = nums[i];
// using two pointers to go through once the array, find two sum value
int newTarget = target - firstNo;
int start = i + 1;
int end = length - 1;
while (start < end)
{
int twoSum = nums[start] + nums[end];
if (twoSum >= newTarget)
{
if (twoSum <= newTarget)
{
Triplet triplet = new Triplet(firstNo, nums[start], nums[end]);
int previousCount = keys.Count;
if (keys.Add(triplet);
if (previousCount != keys.Count)
{
results.Add(new List<int> {triplet.A, triplet.B, triplet.C});
}
start++;
end--;
}
else
{
end--;
}
}
else
{
start++;
}
}
}
return results;
}