This should faster as it skips values already evaluated
Since it skips values evaluated then do not need to check for duplicate
public static IList<IList<int>> ThreeSumB(int[] nums)
{
IList<IList<int>> results = new List<IList<int>>();
if (nums == null)
return results;
int length = nums.Length;
if (length < 3)
return results;
Array.Sort(nums);
Debug.WriteLine(string.Join(", ", nums));
int target = 0;
int firstNo;
int newTarget;
int start;
int end;
for (int i = 0; i < length - 2; i++)
{
firstNo = nums[i];
if (i > 0 && firstNo == nums[i-1])
continue;
// using two pointers to go through once the array, find two sum value
newTarget = target - firstNo;
start = i + 1;
end = length - 1;
while (start < end)
{
int twoSum = nums[start] + nums[end];
if (twoSum < newTarget)
{
//Debug.WriteLine(nums[start] + " " + nums[start + 1]);
start++;
while (start < end && nums[start - 1] == nums[start])
start++;
//Debug.WriteLine(nums[start]);
}
else if (twoSum > newTarget)
{
//Debug.WriteLine(nums[end] + " " + nums[end - 1]);
end--;
while (start < end && nums[end + 1] == nums[end])
end--;
//Debug.WriteLine(nums[end]);
}
else
{
results.Add(new List<int> { firstNo, nums[start], nums[end] });
//Debug.WriteLine(nums[start] + " " + nums[start + 1]);
start++;
while (start < end && nums[start - 1] == nums[start])
start++;
//Debug.WriteLine(nums[start]);
//Debug.WriteLine(nums[end] + " " + nums[end - 1]);
end--;
while (start < end && nums[end + 1] == nums[end])
end--;
// Debug.WriteLine(nums[end]);
}
}
}
return results;
}
I am getting like 8x faster than your using
int[] array = new int[] { -1, 0, 1, 2, -1, -4, -1, -4, 1, 2, 2 };