Skip to content

Commit

Permalink
15
Browse files Browse the repository at this point in the history
  • Loading branch information
retaw committed Sep 5, 2018
1 parent 2d230b1 commit 33108c2
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
68 changes: 68 additions & 0 deletions 15_3_sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ targets = \
12_integer_to_roman.exec\
13_roman_to_integer.exec\
14_longest_common_prefix.exec\
15_3_sum.exec\


CC = g++
Expand Down
7 changes: 7 additions & 0 deletions test.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ using std::string;

using std::vector;
using std::map;
using std::multimap;
using std::unordered_map;
using std::unordered_multimap;

using std::set;
using std::multiset;
using std::unordered_set;
using std::unordered_multiset;

using namespace std::placeholders;

Expand Down

0 comments on commit 33108c2

Please sign in to comment.