lc18. 四数之和

题目链接:18. 四数之和 - 力扣(Leetcode)

题解

双指针,题目中会超过 int

参考代码

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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& a, int s) {
vector<vector<int>>ans;
sort(a.begin(), a.end());
int n = a.size();
for(int i=0; i<n; ++i) {
if(i&&a[i-1]==a[i]) continue;
map<int,int>mp;
for(int j=i+1;j<n;j++) {
if(mp[a[j]]==1) continue;
mp[a[j]] = 1;
long long s1 = (long long)s - a[i] - a[j];
int k=j+1;
int t=n-1;
while(k<t) {
long long s2 = a[k] + a[t];
if(s2==s1) {
vector<int>tmp{a[i], a[j], a[k], a[t]};
ans.push_back(tmp);
int now = a[k];
k++;
while(k<=t&&a[k]==now) k++;
// cout<<k<<" "<<t<<endl;
}
else if(s2<s1) {
k++;
}
else {
t--;
}
}
}
}
return ans;
}
};
作者

Ryen Xiang

发布于

2023-07-15

更新于

2024-08-05

许可协议


网络回响

评论