您的位置:首页 > 其它

LeetCode 笔记系列三 3Sum

2013-07-04 11:47 573 查看
题目: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.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

额外的要求是不能返回重复的triplets,返回的a,b,c的顺序要是非递减的。

解法一:首先想一下,三个数相加,要为0的话,如果不是都为0,那么至少有一个正数一个负数。可以从这一点出发,设置两个指针i和j,分别指向数组S的首尾,always保持numbers[i] <= 0 and numbers[j]>0。哦,对了,数组要先给它排序。然后判断numbers[i] + numbers[j]的符号,如果是大于0,我们就去数组负数部分search,反之去正数部分找。因为数组是sorted,search部分可以用binarySearch。代码如下:

public static ArrayList<ArrayList<Integer>> threeSum2(int[] num) {
Arrays.sort(num);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < num.length - 2;i++){
if(i > 0 && num[i] == num[i-1])continue;
int j = i + 1;
int k = num.length - 1;
while(j < k){
int twoSum = num[i] + num[j];
if(twoSum + num[k] > 0){
k--;
}else if(twoSum + num[k] < 0){
j++;
}else {
addTuple(result,new int[]{num[i],num[j],num[k]});
j++;
k--;
while(num[j] == num[j - 1] && num[k]==num[k+1] && j < k){
j++;
k--;
}
}
}
}
return result;
}


O(n^2)
这道虽然不是那么难,但是要注意的是边界条件的判断和代码的简洁;排序是个好东西。

解法二这种,还可以应用到4Sum,3SumCloset问题中。想对于穷举法,是一种“有计划”的搜索问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: