-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum
More file actions
64 lines (55 loc) · 1.49 KB
/
Copy path3Sum
File metadata and controls
64 lines (55 loc) · 1.49 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
57
58
59
60
61
62
63
64
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& num) {
vector<vector<int> > ret;
if (num.size() == 0) return ret;
sort(num.begin(), num.end());
for (vector<int>::const_iterator it = num.begin();
it != num.end();
++it)
{
// Dedup
if (it != num.begin() && *it == *(it - 1))
{
continue;
}
// Dedup, front = it + 1
vector<int>::const_iterator front = it + 1;
vector<int>::const_iterator back = num.end() - 1;
while (front < back)
{
const int sum = *it + *front + *back;
if (sum > 0)
{
--back;
}
else if (sum < 0)
{
++front;
}
// Dedup
else if (front != it + 1 && *front == *(front - 1))
{
++front;
}
// Dedup
else if (back != num.end() - 1 && *back == *(back + 1))
{
--back;
}
else
{
vector<int> result;
// Already sorted.
result.push_back(*it);
result.push_back(*front);
result.push_back(*back);
ret.push_back(result);
++front;
--back;
}
}
}
return ret;
}
};