diff --git a/include/s0018_4sum.hpp b/include/s0018_4sum.hpp new file mode 100644 index 0000000..a446e24 --- /dev/null +++ b/include/s0018_4sum.hpp @@ -0,0 +1,14 @@ +#ifndef S0018_4SUM +#define S0018_4SUM + +#include +#include + +using namespace std; + +class Solution { + public: + vector> fourSum(vector& nums, int target); +}; + +#endif diff --git a/src/s0018_4sum.cpp b/src/s0018_4sum.cpp new file mode 100644 index 0000000..f203504 --- /dev/null +++ b/src/s0018_4sum.cpp @@ -0,0 +1,28 @@ +#include "s0018_4sum.hpp" + +vector> Solution::fourSum(vector& nums, int target) { + int len = nums.size(); + if (len < 4) { + return {}; + } + vector> result{}; + sort(nums.begin(), nums.end()); + for (int i{1}; i < len - 2; i++) { + for (int j = len - 2; j > i; j--) { + for (int x{0}, y = len - 1; x < i && y > j;) { + if (nums[x] + nums[y] + nums[i] + nums[j] > target) { + y--; + } else if (nums[x] + nums[y] + nums[i] + nums[j] < target) { + x++; + } else { + vector v = {nums[x], nums[i], nums[j], nums[y]}; + if (std::find(result.begin(), result.end(), v) == result.end()) { + result.push_back(v); + } + x++; + } + } + } + } + return result; +} diff --git a/tests/s0018_4sum.cpp b/tests/s0018_4sum.cpp new file mode 100644 index 0000000..03269f4 --- /dev/null +++ b/tests/s0018_4sum.cpp @@ -0,0 +1,19 @@ +#include "s0018_4sum.hpp" + +#include + +TEST(Problem18, Case1) { + vector nums{1, 0, -1, 0, -2, 2}; + int target{0}; + vector> sum{{-2, -1, 1, 2}, {-2, 0, 0, 2}, {-1, 0, 0, 1}}; + Solution solution; + EXPECT_EQ(solution.fourSum(nums, target), sum); +} + +TEST(Problem18, Case2) { + vector nums{2, 2, 2, 2, 2}; + int target{8}; + vector> sum{{2, 2, 2, 2}}; + Solution solution; + EXPECT_EQ(solution.fourSum(nums, target), sum); +}