This commit is contained in:
parent
cc66004929
commit
4ec72db468
14
include/s0016_3sum_closest.hpp
Normal file
14
include/s0016_3sum_closest.hpp
Normal 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
|
27
src/s0016_3sum_closest.cpp
Normal file
27
src/s0016_3sum_closest.cpp
Normal 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;
|
||||
}
|
19
tests/s0016_3sum_closest.cpp
Normal file
19
tests/s0016_3sum_closest.cpp
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user