题面
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
给定数组,找出并返回最接近target的三个元素的和。可以假设,只有一个解。
样例
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路
我们在15题 3Sum中做过,三数加和为target的问题,采用了Two-Point逼近的方法。本题我们稍加改动就可以解决。
1. 数组排序,固定一个元素i,通过两点法去[i+1, size()-1]中搜索另外两个数字,先计算他们的和;
2. 若sum == target,直接返回;若不等,就需要判断sum与 我们给的初值res 那个更加接近target,即判断 abs(sum - target) 与 abs(res - target)的大小,对res进行更新,另外注意 l 和 r 的更新。
3. 返回res.
源码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
if(len < )
return ;
//数组升序排序
sort(nums.begin(), nums.end());
int res = nums[]+nums[]+nums[];
for(int i=; i<len; i++)
{
if(i> && nums[i]==nums[i-])
i++;//避免i的重复,不必要
int l = i+, r = len-;
while(l < r)//两点法搜搜
{
int sum = nums[i] + nums[l] + nums[r];
if(sum == target)
return sum;
else if(sum > target)
{
if(abs(sum - target) < abs(res - target))
res = sum;
r--;
}
else
{
if(abs(sum - target) < abs(res - target))
res = sum;
l++;
}
}
}
return res;
}
};