leetcode/src/s0016_3sum_closest.cpp
2022-11-30 18:20:36 +08:00

28 lines
829 B
C++

#include "s0016_3sum_closest.hpp"
// 和上一道一样,排序 + 双指针
int S0016::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;
}