-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3Sum.cpp
More file actions
54 lines (51 loc) · 1.05 KB
/
15.3Sum.cpp
File metadata and controls
54 lines (51 loc) · 1.05 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
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
static vector<vector<int>> threeSum(vector<int> nums)
{
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (auto iter = nums.begin(); iter != nums.end(); iter++)
{
if (*iter > 0)
break;
if (iter != nums.begin() && *iter == *(iter - 1))
continue;
auto lower = iter + 1, higher = prev(nums.end());
while (lower < higher)
{
int ans = *iter + *lower + *higher;
if (ans > 0)
{
higher--;
while (*higher == *(higher + 1))
higher--;
}
else if (ans < 0)
{
lower++;
while (*lower == *(lower - 1))
lower++;
}
else
{
res.push_back({ *iter, *lower, *higher });
lower++;
higher--;
while (*higher == *(higher + 1))
higher--;
while (*lower == *(lower - 1))
lower++;
}
}
}
return res;
}
};
int main()
{
vector<vector<int>> res = Solution::threeSum({ 2,4,5,12,-5,2,5,-6,1,6,7,-3,-5,-2,6,-8 });
}