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: The solution set must not contain duplicate triplets.
1
2
3
4
5
6
7
8
>For example, given array S = [-1, 0, 1, 2, -1, -4],
先对数组元素进行排序,同样取三个指针,其中两个指针指向较小的两个数,一个指针指向较大的一个数,同样有类似有序双端队列的指针移动操作,但是在内循环外添加了一个准入条件:i == 0 || (i > 0 && num[i] != num[i-1]) ,意思就是,如果有重复的数组元素,那么就跳过,不进行加和与比较,同理,在内循环中也有这一个判断: while (lo < hi && num[lo] == num[lo+1]) lo++; while (lo < hi && num[hi] == num[hi-1]) hi--; ,这样相同的元素就会直接跳过,既节省了时间(加和与比较操作,耗时),同时也保证了结果中不会出现重复的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < num.length-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = num.length-1, sum = 0 - num[i];