15 3Sum

15. 3Sum

1. Question

Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+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
For example, given array S = [-1, 0, 1, 2, -1, -4],
2
3
A solution set is:
4
[
5
[-1, 0, 1],
6
[-1, -1, 2]
7
]
Copied!

2. Implementation

(1) Two Pointers
1
class Solution {
2
public List<List<Integer>> threeSum(int[] nums) {
3
List<List<Integer>> res = new ArrayList<>();
4
Arrays.sort(nums);
5
6
for (int i = 0; i < nums.length - 2; i++) {
7
if (i > 0 && nums[i - 1] == nums[i]) {
8
continue;
9
}
10
11
int j = i + 1, k = nums.length - 1;
12
13
while (j < k) {
14
int sum = nums[i] + nums[j] + nums[k];
15
16
if (sum == 0) {
17
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
18
++j;
19
--k;
20
21
while (j < k && nums[j - 1] == nums[j]) ++j;
22
while (j < k && nums[k] == nums[k + 1]) --k;
23
}
24
else if (sum < 0) {
25
++j;
26
}
27
else {
28
--k;
29
}
30
}
31
}
32
return res;
33
}
34
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n^2)