s0018
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-11-04 16:35:55 +08:00
parent 47099028a2
commit 1de1398897
3 changed files with 61 additions and 0 deletions

14
include/s0018_4sum.hpp Normal file
View File

@ -0,0 +1,14 @@
#ifndef S0018_4SUM
#define S0018_4SUM
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target);
};
#endif

28
src/s0018_4sum.cpp Normal file
View File

@ -0,0 +1,28 @@
#include "s0018_4sum.hpp"
vector<vector<int>> Solution::fourSum(vector<int>& nums, int target) {
int len = nums.size();
if (len < 4) {
return {};
}
vector<vector<int>> 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<int> 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;
}

19
tests/s0018_4sum.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "s0018_4sum.hpp"
#include <gtest/gtest.h>
TEST(Problem18, Case1) {
vector<int> nums{1, 0, -1, 0, -2, 2};
int target{0};
vector<vector<int>> 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<int> nums{2, 2, 2, 2, 2};
int target{8};
vector<vector<int>> sum{{2, 2, 2, 2}};
Solution solution;
EXPECT_EQ(solution.fourSum(nums, target), sum);
}