-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum2.cpp
70 lines (59 loc) · 1.31 KB
/
3Sum2.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
63
64
65
66
67
68
69
70
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Two pinter approach
vector<vector<int>> threeSum(vector<int> &nums)
{
int n = nums.size();
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i++)
{
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int j = i + 1, k = n - 1;
while (j < k)
{
int sum = nums[i] + nums[j] + nums[k];
if (sum < 0)
{
j++;
}
else if (sum > 0)
{
k--;
}
else
{
ans.push_back({nums[i], nums[j], nums[k]});
j++;
k--;
while (j < k && nums[j] == nums[j - 1])
{
j++;
}
}
}
}
return ans;
}
int main()
{
vector<int> nums = {-1, 0, 1, 2, -1, 4};
vector<vector<int>> result = threeSum(nums);
for (const auto &triplet : result)
{
cout << "[";
for (size_t i = 0; i < triplet.size(); ++i)
{
cout << triplet[i];
if (i < triplet.size() - 1)
cout << ", ";
}
cout << "]" << endl;
}
return 0;
}