题目大意:在给出的数组中找出最接近于给定目标的三数之和
分析:K sum问题。和leetcode1、leetcode15类似。本题思路和15一样,就是记录一下当前和与目标的差值即可,找出差值最小值即为答案。
代码:
#include <cmath>
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int minus = 0x3f3f3f3f;
int ans = 0;
for (int i = 0;i < nums.size() - 2;i++) {
int l = i + 1;
int r = nums.size() - 1;
while (l < r) {
if (nums[l] + nums[r] + nums[i] == target) {
return target;
}
else if (nums[l] + nums[r] + nums[i] < target) {
if (minus > abs(nums[l] + nums[r] + nums[i] - target)) {
minus = abs(nums[l] + nums[r] + nums[i] - target);
ans = nums[l] + nums[r] + nums[i];
}
l++;
}
else {
if (minus > abs(nums[l] + nums[r] + nums[i] - target)) {
minus = abs(nums[l] + nums[r] + nums[i] - target);
ans = nums[l] + nums[r] + nums[i];
}
r--;
}
}
}
return ans;
}
};