2022-11-04 07:03:06 +00:00
|
|
|
#include "s0016_3sum_closest.hpp"
|
|
|
|
|
|
|
|
// 和上一道一样,排序 + 双指针
|
|
|
|
|
2022-11-30 10:20:36 +00:00
|
|
|
int S0016::threeSumClosest(vector<int>& nums, int target) {
|
2022-11-04 07:03:06 +00:00
|
|
|
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;
|
|
|
|
}
|