18 四数之和

本文最后更新于:2022年8月31日 凌晨

给定一个包含 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]
]

Solution

参考:[15 三数之和](15 三数之和.md) 、**@Sean-87**

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
# @lc code=start
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums = sorted(nums)
length = len(nums)
if not nums or length<4: return []
res = []
def twoSum(nums, start, target):
low, high = start, len(nums)-1
res = []
while low<high:
sumLR = nums[low]+nums[high]
left, right = nums[low], nums[high]
if sumLR<target:
while low<high and nums[low]==left: low+=1
elif sumLR>target:
while low<high and nums[high]==right: high-=1
else:
res.append([left, right])
while low<high and nums[low]==left: low+=1
while low<high and nums[high]==right: high-=1
return res

for a in range(len(nums)-3):
# a>0 和 b>a+1 为了跳过最初始状况,如 [0,0,0,0]
if a>0 and nums[a]==nums[a-1]: continue
for b in range(a+1, len(nums)-2):
if b>a+1 and nums[b]==nums[b-1]: continue
subRes = twoSum(nums, b+1, target-nums[a]-nums[b])
for sub in subRes:
sub.append(nums[a])
sub.append(nums[b])
res.append(sub)
return res
# @lc code=end

cpp

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
53
54
55
// @lc code=start
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if(nums.size()<4) return res;

sort(nums.begin(), nums.end());
// if(nums[0]>target) return res;

for(int i=0; i<nums.size()-3; i=nextIndex(nums, i)){
for(int j=i+1; j<nums.size()-2; j=nextIndex(nums, j)){
int t = target-nums[i]-nums[j];
vector<vector<int>> subRes = twoSum(nums, j+1, t);
for(auto sub : subRes){
sub.push_back(nums[j]);
sub.push_back(nums[i]);
res.push_back(sub);
}
}
}
return res;
}

private:
vector<vector<int>> twoSum(vector<int>& nums, int start, int target) {
vector<vector<int>> result;
int left=start, right=nums.size()-1;
while(left<right){
int sum = nums[left]+nums[right];
int low = nums[left], high = nums[right];
if(sum <target){
while(left<right && nums[left]==low) left+=1;
}
else if(sum>target){
while(left<right && nums[right]==high) right-=1;
}
else{
result.push_back({nums[left], nums[right]});
while(left<right && nums[left]==low) left+=1;
while(left<right && nums[right]==high) right-=1;
}
}
return result;
}

int nextIndex(const vector<int>& nums, int index){
for(int i=index+1; i<nums.size(); ++i){
if(nums[i] != nums[index])
return i;
}
return nums.size();
}
};
// @lc code=end

参考:代码随想录

  • 用双指针法
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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int k = 0; k < nums.size(); k++) {
// 剪枝处理
if (nums[k] > target && nums[k] >= 0 && target >= 0) {
break; // 这里使用break,统一通过最后的return返回
}
// 对nums[k]去重
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
for (int i = k + 1; i < nums.size(); i++) {
// 2级剪枝处理
if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0 && target >= 0) {
break;
}

// 对nums[i]去重
if (i > k + 1 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (right > left) {
// nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出
if ((long) nums[k] + nums[i] + nums[left] + nums[right] > target) {
right--;
// nums[k] + nums[i] + nums[left] + nums[right] < target 会溢出
} else if ((long) nums[k] + nums[i] + nums[left] + nums[right] < target) {
left++;
} else {
result.push_back(vector<int>{nums[k], nums[i], nums[left], nums[right]});
// 对nums[left]和nums[right]去重
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;

// 找到答案时,双指针同时收缩
right--;
left++;
}
}

}
}
return result;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!