Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解答:
这道题其实就是硬算。不用动归。但是还是有技巧的,就是先sort后,这样左右夹击就可以根据sum与target的情况来走了。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end(),greater<int>());
int sum=nums[0]+nums[1]+nums[2];
int begin=0;
int n=nums.size();
int newdiff=0;
int diff=abs(sum-target);
int result=sum;
while(begin<n)
{
int left=begin+1,right=n-1;
while(left<right)
{
sum=nums[begin]+nums[left]+nums[right];
newdiff=abs(sum-target);
if(newdiff< diff){ diff=newdiff; result=sum; }
if(sum-target>0) left++;
else right--;
}
begin++;
}
return result;
}
};