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)
思路:等同于求两个数和的相反数是否存在于这个数组中。可以延伸到K sum的问题。
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(num);
int start = 0;
while (start < num.length-2) {
if (start == 0 || num[start] != num[start-1] ) {
//留意判断条件,之前写的是start与start+1不等,导致一直不对。。
int instart = start+1;
int inlast = num.length-1;
while (instart < inlast) {
if (num[instart] + num[inlast] == -num[start]) {//这里可以考虑用二分法查找来优化。
List<Integer> temp = new ArrayList<Integer>();
temp.add(num[start]);
temp.add(num[instart]);
temp.add(num[inlast]);
list.add(temp);
do {
inlast--;//重复的数在这里直接跳过。
} while (num[inlast] == num[inlast+1] && instart < inlast);
do{
instart++;
} while(num[instart] == num[instart-1] && instart < inlast);
}else if (num[instart] + num[inlast] > -num[start]) {
inlast--;
}else {
instart++;
}
}
}
start++;
}
return list;
}
}
Runtime: 358 ms
更多收获可参考(个人觉得很棒):Summary for LeetCode 2Sum, 3Sum, 4Sum, K Sum