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).
意思:他的大概意思是说给定一个数组和一个target,寻找出3个相加的值最接近target的三个数。
思路:其实和之前的3Sum差不多,只是要求的值是最接近的,我们可以不断地比较值的绝对值最接近于target的那个数就是我们要求的
代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closetarget =nums[0]+nums[1]+nums[2];
if(closetarget==target||nums.size()==3) return closetarget;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
int front =i+1;
int back=nums.size()-1;
while(front<back){
int sum =nums[i]+nums[front]+nums[back];
if(abs(closetarget-target)>abs(sum-target)){
closetarget =sum;
}
if(sum<target) front++;
else if(sum>target) back--;
else return sum;
}
}
return closetarget;
}
};