给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)
public class Solution {
/*
* @param numbers: Give an array numbers of n integer
* @return: Find all unique triplets in the array which gives the sum of zero.
*/
public List<List<Integer>> threeSum(int[] numbers) {
// write your code here
Arrays.sort(numbers);
List<List<Integer>> re = new ArrayList<>();
for (int i = 0; i < numbers.length - 2; ++i) {
int left = i + 1;
int right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
int target = -numbers[i];
if (sum < target) {
while (left < right && numbers[left + 1] == numbers[left])
left++;
left++;
} else if (sum > target) {
while (left < right && numbers[right - 1] == numbers[right])
right--;
right--;
} else {
List<Integer> temp = new ArrayList<>(Arrays.asList(numbers[i], numbers[left], numbers[right]));
re.add(temp);
while (left < right && numbers[left + 1] == numbers[left])
left++;
left++;
while (left < right && numbers[right - 1] == numbers[right])
right--;
right--;
}
}
while (i < numbers.length - 2 && numbers[i] == numbers[i + 1])
i++;
}
return re;
}
}