给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:先将数组排序,再确定数组的第一个数字为三数之一,剩余两个数字在数组中通过左右比较依次判断,接着在确定数组的第二个数字为三数之一…依次判断。
class Solution {
public List<List<Integer>> threeSum(int[] nums)
{
List<List<Integer>> res=new ArrayList<>();
Arrays.sort(nums);
int compare;
for(int i=0;i<nums.length-2;i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;//防止出现相同的数据,数组已经排好序
int left=i+1,right=nums.length-1;
while(left<right)
{
List<Integer> list=new ArrayList<>();
compare=nums[i]+nums[left]+nums[right];
if(compare>0)
{
right--;
}
else if(compare<0)
{
left++;
}
else if(compare==0)
{
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left++;
right--;
while(left<right&&nums[left]==nums[left-1])//防止出现相同的数据
left++;
while(left<right&&nums[right]==nums[right+1])
right--;
}
}
}
return res;
}
}