-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path15_3_sum.cpp
68 lines (55 loc) · 1.18 KB
/
15_3_sum.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
#include "test.h"
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> ret;
if (nums.size() < 3)
return ret;
sort(nums.begin(), nums.end());
for (auto i = 0u; i < nums.size() - 2; )
{
if (nums[i] > 0)
break;
auto j = i + 1;
auto k = nums.size() - 1;
while (j < k)
{
auto sum = nums[i] + nums[j] + nums[k];
if (sum == 0)
{
ret.push_back({nums[i], nums[j++], nums[k--]});
//in the current while loop, i is constant, so make sure the next nums[j] is not equal to the current one
while (nums[j] == nums[j - 1] && j < k)
++j;
//the same operation for k with the same reason
while (nums[k] == nums[k + 1] && j < k)
--k;
}
else
sum < 0 ? ++j : --k;
}
//make sure the next nums[i] is not equal to the current one
++i;
while (nums[i - 1] == nums[i] && i < j )
++i;
}
return ret;
}
};
int main()
{
vector<vector<int>> datas =
{
{-1, 0, 1, 2, -1, -4},
{0, 0 , 0},
{0, 0 , 0, 0},
{-2,0,1,1,2},
{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6},
{},
};
Solution s;
for (auto& data : datas)
cout << s.threeSum(data) << endl;
return 0;
}