-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum.txt
29 lines (29 loc) · 1005 Bytes
/
3Sum.txt
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
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > rets;
if (num.size() < 3)
return rets;
sort(num.begin(), num.end());
for (size_t i = 0; i < num.size() - 2; i++) {
if ((i > 0) && (num[i] == num[i-1]))
continue;
size_t l = i + 1, u = num.size() - 1;
while (l < u) {
long long sum = (long long)num[i] + num[l] + num[u];
if (sum == 0) {
rets.push_back(vector<int> (3, num[i]));
rets.back()[1] = num[l];
rets.back()[2] = num[u];
}
if (sum < 0)
while ((++l < u) && (num[l] == num[l-1]));
else
while ((--u > l) && (num[u] == num[u+1]));
}
}
return rets;
}
};