题目描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
代码
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
IList<IList<int>> result = new List<IList<int>>();
if (nums == null || nums.Length < 3)
return result;
int length = nums.Length;
nums = nums.OrderBy(a => a).ToArray();
for (int i = 0; i < length; i++)
{
int left = i + 1;
int right = length - 1;
if (i > 0 && nums[i] == nums[i - 1])
continue; // 去重
while (left < right)
{
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0)
{
result.Add(new List<int>() {nums[i], nums[left], nums[right]});
while (nums[left] == nums[left + 1])
left++;
while (nums[right - 1] == nums[right])
right--;
left++;
right--;
}
else if (sum < 0)
left++;
else if (sum > 0)
right--;
}
}
return result;
}
}