Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)DFS递归太深会超时,选用两层for循环
将3个和问题,转化为两个和的问题(两个指针指向数组)
注意去重:
- if (i > 0 或类似condition && num[i] == num[i - 1]) continue;
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
if(num == null) return null;
Arrays.sort(num);
int len = num.length;
for(int i=0; i<len; i++){
if(i>0 && num[i] == num[i-1]) continue;//for No duplicate
int p=i+1, q=len-1;
while(p < q){//2 wei
if(p!=i+1 && num[p]==num[p-1]){//for No duplicate
p++;
continue;
}
if(q!=len-1 && num[q]==num[q+1]){//for No duplicate
q--;
continue;
}
int sum = num[p] + num[q] + num[i];
if(sum == 0){
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(num[i]);
l.add(num[p]);
l.add(num[q]);
res.add(l);
p++;
}
else if(sum < 0) p++;
else q--;
}
}
return res;
}
}