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

This commit is contained in:
Sainnhe Park 2022-11-04 15:03:06 +08:00
parent cc66004929
commit 4ec72db468
3 changed files with 60 additions and 0 deletions

View File

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

View File

@ -0,0 +1,27 @@
#include "s0016_3sum_closest.hpp"
// 和上一道一样,排序 + 双指针
int Solution::threeSumClosest(vector<int>& nums, int target) {
int sum = nums[0] + nums[1] + nums[2];
int len = nums.size();
sort(nums.begin(), nums.end());
for (int i{1}; i < len - 1; i++) {
for (int j{0}, k = len - 1; j != k && i != j && i != k;) {
if (nums[i] + nums[j] + nums[k] > target) {
if (abs(nums[i] + nums[j] + nums[k] - target) < abs(sum - target)) {
sum = nums[i] + nums[j] + nums[k];
}
k--;
} else if (nums[i] + nums[j] + nums[k] < target) {
if (abs(nums[i] + nums[j] + nums[k] - target) < abs(sum - target)) {
sum = nums[i] + nums[j] + nums[k];
}
j++;
} else {
return nums[i] + nums[j] + nums[k];
}
}
}
return sum;
}

View File

@ -0,0 +1,19 @@
#include "s0016_3sum_closest.hpp"
#include <gtest/gtest.h>
TEST(Problem16, Case1) {
vector<int> nums{-1, 2, 1, -4};
int target{1};
int o{2};
Solution solution;
EXPECT_EQ(solution.threeSumClosest(nums, target), o);
}
TEST(Problem16, Case2) {
vector<int> nums{0, 0, 0};
int target{1};
int o{0};
Solution solution;
EXPECT_EQ(solution.threeSumClosest(nums, target), o);
}