5. 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size();
if (size < 3) return 0;
sort(nums.begin(), nums.end());
int actural_num = size - 2;
//遍历这些数
int min = INT_MAX;
int result = 0;//最佳结果
for (size_t i = 0; i < actural_num; i++)
{
if (i > 0 && nums[i] == nums[i - 1]) continue;
int picked = nums[i];
int left = i + 1;
int right = size - 1;
while (left<right)
{
int sum = picked + nums[left] + nums[right];
int diff = sum - target;
if (abs(diff) < abs(min))
{
min = abs(diff);
result = sum;
}
if (sum >target)
{
--right;
}
else if (sum < target)
{
++left;
}
else
{
return target;
}
}
}
return result;
}
};