lc.四数之和
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
提示:
1
2
3
|
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
|
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
|
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
//a + b + c + d == target ->
//d == target - a - b - c - d
vector<vector<int>> res;
int n = nums.size();
if(n<4) return res;
for(int i=0;i<n;i++) {
if(nums[i] > 0 && nums[i] > target) break;
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 a = nums[i], b= nums[j];
int l = j+1,r = n-1;
while(l<r) {
int c = nums[l],d = nums[r];
if((long long) a+b+c+d == target) {
res.push_back({a,b,c,d});
while(l<r && nums[l] == nums[l+1]) ++l;
while(l<r && nums[r] == nums[r-1]) --r;
++l;
}else if((long long)a+b+c+d> target) {
--r;
}else {
// < target
++l;
}
}
}
}
return res;
}
};
|