三数之和
给你一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 *a,b,c ,*使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
**注意:**答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思想:
排序+去重
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (nums == null || nums.length <3) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length-2; i++) {
int l = i+1;
int r = nums.length-1;
while(l<r) {
int tmp = nums[i] + nums[l] + nums[r];
if (tmp == 0) {
List<Integer> p = new ArrayList<>();
p.add(nums[i]);
p.add(nums[l]);
p.add(nums[r]);
res.add(p);
// 去重
while(l+1<nums.length && nums[l]==nums[l+1]) {l++;}
while(r-1>i && nums[r] == nums[r-1]) {r--;}
l++;r--;
}else if(tmp>0) {
r--;
}else {
l++;
}
}
//去重
while(i<nums.length-2 && nums[i] == nums[i+1]) {
i++;
}
}
return res;
}