和三数之和很类似,同理排序后固定第一个数,然后双指针即可,同时根据差值的绝对值是否更小决定是否更新返回的res
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int min_number = INT_MAX;
int res = 0;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int lo = i + 1, hi = n - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
if (abs(sum - target) < min_number) {
min_number = abs(sum - target);
res = sum;
}
if (sum < target) lo++;
else if (sum > target) hi--;
else return target;
}
}
return res;
}
};