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)
Subscribe to see which companies asked this question
先排序 然后确定第一个数(其实从前往后数就行),然后后两个数一个从第一个数往后走 一个从最后一个数往前走 和大于0就第三个数往前走 反之第二个数往后走
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> ret = new ArrayList<>();
int len = num.length, tar = 0;
if (len <= 2)
return ret;
Arrays.sort(num);
for (int i = 0; i <= len - 3; i++) {
// first number : num[i]
int j = i + 1; // second number
int k = len - 1; // third number
while (j < k) {
if (num[i] + num[j] + num[k] < tar) {
++j;
} else if (num[i] + num[j] + num[k] > tar) {
--k;
} else {
ret.add(Arrays.asList(num[i], num[j], num[k]));
++j;
--k;
// folowing 3 while can avoid the duplications
while (j < k && num[j] == num[j - 1])
++j;
while (j < k && num[k] == num[k + 1])
--k;
}
}
while (i <= len - 3 && num[i] == num[i + 1])
++i;
}
return ret;
}
}