-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum.cpp
More file actions
34 lines (33 loc) · 974 Bytes
/
3sum.cpp
File metadata and controls
34 lines (33 loc) · 974 Bytes
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
// 3Sum
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > ret;
if(num.size() < 3) return ret;
sort(num.begin(), num.end());
int k, l;
for(int i = 0; i <= num.size() - 3;) {
k = i+1;
l = num.size()-1;
while(k < l) {
int tsum = num[i] + num[k] + num[l];
if(tsum > 0) {
l--;
} else if(tsum < 0) {
k++;
} else {
vector<int> r(3);
r[0] = num[i];
r[1] = num[k];
r[2] = num[l];
ret.push_back(r);
int tl = num[l];
while(num[--l] == tl);
}
}
int ti = num[i];
while(num[++i] == ti);
}
return ret;
}
};