diff --git a/15_3_sum.cpp b/15_3_sum.cpp new file mode 100644 index 0000000..1346886 --- /dev/null +++ b/15_3_sum.cpp @@ -0,0 +1,68 @@ +#include "test.h" + + +class Solution { +public: + vector> threeSum(vector& nums) + { + vector> 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> 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; +} diff --git a/Makefile b/Makefile index ce51a5b..b43a8f6 100644 --- a/Makefile +++ b/Makefile @@ -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++ diff --git a/test.h b/test.h index d2f7cfd..89ea89f 100644 --- a/test.h +++ b/test.h @@ -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;