LeetCode18-四数之和

题目链接

英文链接:https://leetcode.com/problems/4sum/

中文链接:https://leetcode-cn.com/problems/4sum/

题目详述

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a, b,cd ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

1
2
3
4
5
6
7
8
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

题目详解

LeetCode15-三数之和 现在变成了四数之和,同样的思想运用双指针。

  • 首先把数组从小到大进行排序。
  • 遍历过程中固定个元素。
  • 再运用双指针的思想,一个从左往右扫描,一个从右往左扫描。
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
public class LeetCode_00018 {

public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; ++i) {
// 避免重复
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n; ++j) {
// 避免重复
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int l = j + 1;
int r = n - 1;
while (l < r) {
int sum = nums[i] + nums[j] + nums[l] + nums[r];
if (sum > target) { // 因为数组有序,说明右侧的数过大,所以下标左移
--r;
} else if (sum < target) { // 因为数组有序,说明左侧的数过小,所以下标右移
++l;
} else {
res.add(Arrays.asList(nums[i], nums[j], nums[l++], nums[r--]));
// 两侧的下标向中间移动,直到不与之前取出的数相同,避免重复
while (l < r && nums[l] == nums[l - 1]) {
++l;
}
while (l < r && nums[r] == nums[r + 1]) {
--r;
}
}
}
}
}
return res;
}
}