问题描述
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
- 3 <= nums.length <= 10^3
- -10^3
- <= nums[i] <=
- 10^3
- -10^4
- <= target <=
- 10^4
解法
「最接近」即为差值的绝对值最小。
借助双指针,我们就可以对枚举的过程进行优化。我们用 p
b 和p c分别表示指向 b 和 c 的指针,初始时,p b指向位置i+1,即左边界;p c 指向位置 n−1,即右边界。在每一步枚举的过程中,我们用 a+b+c 来更新答案,并且:
如果a+b+c≥target,那么就将 pc向左移动一个位置;如果 a+b+c<target,那么就将pb向右移动一个位置。
当我们枚举到恰好等于target 的 a+b+c 时,可以直接返回 target 作为答案,因为不会有再比这个更接近的值了。
另一个优化与 15. 三数之和的官方题解 中提到的类似。当我们枚举 a,b,c 中任意元素并移动指针时,可以直接将其移动到下一个与这次枚举到的不相同的元素,减少枚举的次数。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
int best = 1e7; // best来更新最接近的三数之和
// 根据差值的绝对值来更新答案
// 这种函数头部没有见过
auto update = [&](int cur) {
if (abs(cur - target) < abs(best - target)) {
best = cur;
}
};
// 枚举 a
for (int i = 0; i < n; ++i) {
// 保证和上一次枚举的元素不相等
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// 使用双指针枚举 b 和 c
int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
// 如果和为 target 直接返回答案
if (sum == target) {
return target;
}
update(sum);
if (sum > target) {
// 如果和大于 target,移动 c 对应的指针
int k0 = k - 1;
// 移动到下一个不相等的元素
// j<k0 这个条件不知道为什么加上
while (j < k0 && nums[k0] == nums[k]) {
--k0;
}
k = k0;
}
else {
// 如果和小于 target,移动 b 对应的指针
int j0 = j + 1;
// 移动到下一个不相等的元素
// j0<k 这个条件不知道为什么加上
while (j0 < k && nums[j0] == nums[j]) {
++j0;
}
j = j0;
}
}
}
return best;
}
};