leetcode/src/s0016_3sum_closest.cpp

28 lines
832 B
C++
Raw Normal View History

2022-11-04 07:03:06 +00:00
#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;
}