18. 4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + 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
2
3
4
5
6
7
8
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

解法1: O(N^3)

和3Sum一样的思路,最外层遍历第一个数,第二层遍历第二个数,之后用双指针像中间扫描。遇到加和为target的就推入list中。要注意的是需要去重。那么每一次去重的时候只需要跳过和前一个一样的数就可以了。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int n = nums.length;
if (n < 4) {
return res;
}
Arrays.sort(nums); // need to sort first
for (int i = 0; i < n - 3; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n - 2; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1;
int m = n - 1;
while (k < m) {
while (k != j + 1 && k < m && nums[k] == nums[k - 1]) {
k++; // remove duplicates
}
while (m != n - 1 && k < m && nums[m] == nums[m + 1]) {
m--;
}
if (k < m) {
int sum = nums[i] + nums[j] + nums[k] + nums[m];
if (sum == target) {
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
temp.add(nums[m]);
res.add(temp);
k++;
m--;
} else if (sum < target) {
k++;
} else {
m--;
}
}
}
}
}
return res;
}
}