16. 最接近的三数之和(哈希表就没用了,只能双指针)
题目:给定一个包括 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
//因为这里是最接近,所以没法使用哈希表,只能使用双指针法
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
//排序
sort(nums.begin(),nums.end());
//与target的差值参考
int diff = abs(nums[0] + nums[1] + nums[2] -target);
int res = nums[0] + nums[1] + nums[2];
for(int i = 0; i < nums.size() ; i++)//确定一个基本固定点i,依次往后面遍历,后面数组使用双指针
{
//设立左右指针
int l = i + 1;
int r = nums.size()-1;
while(l < r)
{
//出现等于target的情况
if(nums[i] + nums[l] + nums[r] == target) return nums[i] + nums[l] + nums[r];
//判断与target的差值与参照对比,去差值最小为准
if(abs(nums[i] + nums[l] + nums[r] - target) < diff)
{
diff = abs(nums[i] + nums[l] + nums[r] - target);
res = nums[i] + nums[l] + nums[r];
}
//左右指针的移动情况判断
if(nums[i] + nums[l] + nums[r] < target) l++;
else r--;
}
}
return res;
}
};
613

被折叠的 条评论
为什么被折叠?



