Skip to content

Commit 33108c2

Browse files
committed
15
1 parent 2d230b1 commit 33108c2

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

15_3_sum.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include "test.h"
2+
3+
4+
class Solution {
5+
public:
6+
vector<vector<int>> threeSum(vector<int>& nums)
7+
{
8+
vector<vector<int>> ret;
9+
10+
if (nums.size() < 3)
11+
return ret;
12+
13+
sort(nums.begin(), nums.end());
14+
15+
for (auto i = 0u; i < nums.size() - 2; )
16+
{
17+
if (nums[i] > 0)
18+
break;
19+
20+
auto j = i + 1;
21+
auto k = nums.size() - 1;
22+
while (j < k)
23+
{
24+
auto sum = nums[i] + nums[j] + nums[k];
25+
26+
if (sum == 0)
27+
{
28+
ret.push_back({nums[i], nums[j++], nums[k--]});
29+
30+
//in the current while loop, i is constant, so make sure the next nums[j] is not equal to the current one
31+
while (nums[j] == nums[j - 1] && j < k)
32+
++j;
33+
34+
//the same operation for k with the same reason
35+
while (nums[k] == nums[k + 1] && j < k)
36+
--k;
37+
}
38+
else
39+
sum < 0 ? ++j : --k;
40+
}
41+
42+
//make sure the next nums[i] is not equal to the current one
43+
++i;
44+
while (nums[i - 1] == nums[i] && i < j )
45+
++i;
46+
}
47+
return ret;
48+
}
49+
};
50+
51+
52+
53+
int main()
54+
{
55+
vector<vector<int>> datas =
56+
{
57+
{-1, 0, 1, 2, -1, -4},
58+
{0, 0 , 0},
59+
{0, 0 , 0, 0},
60+
{-2,0,1,1,2},
61+
{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6},
62+
{},
63+
};
64+
Solution s;
65+
for (auto& data : datas)
66+
cout << s.threeSum(data) << endl;
67+
return 0;
68+
}

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ targets = \
1313
12_integer_to_roman.exec\
1414
13_roman_to_integer.exec\
1515
14_longest_common_prefix.exec\
16+
15_3_sum.exec\
1617

1718

1819
CC = g++

test.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,14 @@ using std::string;
3737

3838
using std::vector;
3939
using std::map;
40+
using std::multimap;
4041
using std::unordered_map;
42+
using std::unordered_multimap;
43+
44+
using std::set;
45+
using std::multiset;
46+
using std::unordered_set;
47+
using std::unordered_multiset;
4148

4249
using namespace std::placeholders;
4350

0 commit comments

Comments
 (0)