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.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题目意思:就是求和taget最接近的3sum的值 。
思路:和3sum一样,还是首先排序,然后遍历vector,然后使用two pointers,只不过这里要每次和最小间隔进行比较,然后进行更新。。
代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int ans;
int l,r;
int min_width = 10000000;
sort(nums.begin(),nums.end());
int size = nums.size();
for(int i=0;i<size;i++)
{
int tar = target - nums[i];
l = i+1;
r = size-1;
while(l<r)
{
if(abs(nums[l]+nums[r]-tar)<min_width)
{
ans = nums[l]+nums[r]+nums[i];
min_width = abs(nums[l] + nums[r]-tar);
}
if(nums[l]+nums[r]>tar) r--;
else if(nums[l]+nums[r]<tar) l++;
else
{
ans = target;
min_width = 0;
break;
}
}
}
return ans;
}
};