您的位置:首页 > 其它

3Sum

2014-02-06 05:28 218 查看
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.

public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num.length<=2) return res;
Arrays.sort(num);
int len = num.length;
for(int i=0;i<len;i++){
int sum = 0-num[i];
int start = i+1;
int end = len-1;
while(start<end){
if(num[start]+num[end]<sum){
start++;
}
else if(num[start]+num[end]>sum){
end--;
}
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]); temp.add(num[start]); temp.add(num[end]);
res.add(temp);
start++;end--;
while(start<end && num[start-1]==num[start]){
start++;
}
while(start<end && num[end+1]==num[end]){
end--;
}
}
}
while(i<len-1 &&num[i+1]==num[i]){
i++;
}
}
return res;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: