-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path3sum.cpp
More file actions
56 lines (45 loc) · 1.1 KB
/
3sum.cpp
File metadata and controls
56 lines (45 loc) · 1.1 KB
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
56
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > results;
int i = 0;
int size = num.size();
sort(num.begin(), num.end());
while (i < (size - 2)) {
int pre_number = num[i];
int start = i + 1;
int end = size - 1;
while (start < end) {
int left_val = num[start];
int right_val = num[end];
int sum = pre_number + left_val + right_val;
if (sum < 0) {
++start;
}
else if (sum > 0) {
--end;
}
else {
vector<int> result;
result.push_back(num[i]);
result.push_back(left_val);
result.push_back(right_val);
results.push_back(result);
++start;
--end;
while ((start < end) && (num[start] == left_val)) {
++start;
}
while ((start < end) && (num[end] == right_val)) {
--end;
}
}
}
++i;
while ((i < (size - 2)) && (num[i] == pre_number)) {
++i;
}
}
return results;
}
};