题目
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int length = nums.length;
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(length < 3){
return res;
}
Arrays.sort(nums);
for(int i = 0; i < length-2; i++){
int a = nums[i];
if(i > 0 && a == nums[i-1]){
continue;
}
for(int j = i+1; j < length-1; j++){
int b = nums[j];
if(b == nums[j-1] && j-1 != i){
continue;
}
int cpl = length-1;
int obj = -a-b;
while(cpl != j && nums[cpl] >= obj){
if(nums[cpl] == obj){
List<Integer> list = new ArrayList<>();
list.add(a);
list.add(b);
list.add(nums[cpl]);
res.add(list);
break;
}
else{
cpl--;
}
}
}
}
return res;
}
}