题目描述:
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 arraywhich 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)
public class Three_Sum {
public static ArrayList<int []> threeSum(int array[])
{
ArrayList<int []> result=new ArrayList<int []>();
//这里排序是为了后面两个标记的移动
Arrays.sort(array);
//这里取array.length-2为上限是为了给两个标记留下空间
//如果i到达array.length-3,array.length-2标记start,array.length-1标记end
for(int i=0;i<array.length-2;i++)
{
//这里排除的array[i]的重复
//类似例子中的两个-1
if(i>0&&array[i]==array[i-1])
{
continue;
}
int start=i+1;
int end=array.length-1;
while(end>start)
{
//这里排除的array[start]的重复
if(start>i+1&&array[start]==array[start-1])
{
start++;
continue;
}
//这里排除的array[end]的重复
if(end<array.length-1&&array[end]==array[end+1])
{
end--;
continue;
}
int sum=array[i]+array[start]+array[end];
if(sum==0)
{
int num[]=new int[3];
num[0]=array[i];
num[1]=array[start];
num[2]=array[end];
result.add(num);
//探索所有情况
start++;
end--;
}
if(sum>0)
{
end--;
}
if(sum<0)
{
start++;
}
}
}
return result;
}
public static void main(String[] args) {
int num[]={-3,-2,-2,0,0,0,2,2,3,3};
for(int i=0;i<threeSum(num).size();i++)
{
for(int j=0;j<threeSum(num).get(i).length;j++)
{
System.out.print(threeSum(num).get(i)[j]+" ");
}
System.out.print("\n");
}
}
}