-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3sum.cpp
62 lines (53 loc) · 1.4 KB
/
3sum.cpp
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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> output;
set<vector<int>> s;
for (long i = 0; i < nums.size(); i++)
{
if (nums[i] > 0)
{
break;
}
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int num1 = nums[i];
int left_ptr = i + 1;
int right_ptr = nums.size() - 1;
int target = 0;
while (left_ptr < right_ptr)
{
int total = nums[left_ptr] + nums[right_ptr] + num1;
if (total == target)
{
vector<int> result = {num1, nums[left_ptr],
nums[right_ptr]};
auto itr = s.find(result);
s.insert(result);
left_ptr++;
right_ptr--;
}
else if (total < target)
{
left_ptr++;
}
else
{
right_ptr--;
}
}
}
for (auto trips : s)
{
output.push_back(trips);
}
return output;
}
};