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)
假设数组为num,长度为len
1.使用快速排序数组num
2.依次取一个数num[i],再剩下的数num[i+1]~num[len-1]中使用二分搜索查找两个数,它们的和等于-num[i]。
3.注意去重
public class Solution {
public void quickSort(int [] num, int start, int end){
int point=num[start];
int left=start;
int right=end;
while(left<right){
while(num[right]>=point&&left<right){
right--;
}
if(left<right){
num[left]=num[right];
}
while(num[left]<=point&&left<right){
left++;
}
if(left<right){
num[right]=num[left];
}
}
num[left]=point;
if(left-1>start){
quickSort(num,start,left-1);
}
if(right+1<end){
quickSort(num,right+1,end);
}
}
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> rs=new ArrayList<List<Integer>>();
if(num==null){
return null;
}
if(num.length==0){
return rs;
}
int end=num.length-1;
quickSort(num,0,end);
for(int i=0;i<=end-2;i++){
while(i>0&&i<=end-2&&num[i]==num[i-1]){
i++;
}
int sum=num[i];
int p=i+1;
int q=end;
while(p<q){
while(q<end&&p<q&&num[q]==num[q+1]){
q--;
}
while(p>i+1&&p<q&&num[p]==num[p-1]){
p++;
}
if(p<q){
int tmp=num[p]+num[q]+sum;
if(tmp>0){
q--;
}else if(tmp<0){
p++;
}else{
List<Integer> list=new ArrayList<Integer>();
list.add(sum);
list.add(num[p]);
list.add(num[q]);
rs.add(list);
p++;
}
}
}
}
return rs;
}
}