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)
找数组中能够相加等于0的三个数;和2sum类似 零减去第一个数值 就是2sum了
注意 不能有重复数据 用list做
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
private ArrayList<ArrayList<Integer>> list;
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
list = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);
for(int i=0;i<=num.length-3;i++)
{
if(i>0 && num[i]==num[i-1])
continue;
find(i+1,num.length-1,i,-num[i],num);
}
return list;
}
private void find(int start,int end,int i,int result,int[] num) {
while(start<end)
{
if(num[start]+num[end]>result)
{
end--;
}
else if(num[start]+num[end]<result)
{
start++;
}
else if(num[start]+num[end]==result)
{
ArrayList<Integer> tmpList = new ArrayList<Integer>();
tmpList.add(num[i]);
tmpList.add(num[start]);
tmpList.add(num[end]);
list.add(tmpList);
start++;
end--;
while(start<end && num[start]==num[start-1])
start++;
while(start<end && num[end]==num[end+1])
end--;
}
}
}
}