18 4Sum

18. 4Sum

1. Question

Given an arraySofnintegers, are there elementsa,b,c, anddinSsuch thata+b+c+d= target? Find all unique quadruplets in the array which gives the sum of target.
Note:The solution set must not contain duplicate quadruplets.
1
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
2
3
A solution set is:
4
[
5
[-1, 0, 0, 1],
6
[-2, -1, 1, 2],
7
[-2, 0, 0, 2]
8
]
Copied!

2. Implementation

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

3. Time & Space Complexity

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