题目:最接近的三数之和
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:
输入:nums = [0,0,0], target = 1
输出:0
提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104
https://leetcode.cn/problems/3sum-closest/
思路:sort + 双指针
与三数之和题比较类似,排序后的双指针,右指针往左移动,右指针指向的数值会变小。左指针往右移动,左指针指向的数值会变大。
代码:击败了27.22%
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int best = 1e7;
int size = nums.size();
auto update = [&](int sum) {
if (abs(sum - target) < abs(best - target)) {
best = sum;
}
};
for (int first = 0; first < size; first++) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int third = size - 1;
int second = first + 1;
while (second < third) {
int sum = nums[first] + nums[second] + nums[third];
if (sum == target) {
return target;
}
update(sum);
if (sum > target) {
int third0 = third - 1;
while (second < third0 && nums[third0] == nums[third]) {
--third0;
}
third = third0;
} else {
int second0 = second + 1;
while (second0 < third && nums[second0] == nums[second]) {
++second0;
}
second = second0;
}
}
}
return best;
}
};
总结
与三数之和题比较类似,排序后的双指针,右指针往左移动,右指针指向的数值会变小。左指针往右移动,左指针指向的数值会变大。
该题双指针思想也与第十一题“盛最多水的容器”类似
谢谢观看,祝顺利!