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).
思路:
1. 和3sum类似,求和不等于一个确定的值,但是要找出求和之后与target距离最小的这个和。如何用程序或数学语言表示这个距离最小呢?还是要用two pointer。
2. 参考3sum的分析!
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size();
if(n<3) return 0;
sort(nums.begin(),nums.end());
int diff=INT_MAX,sum=0;
for(int i=0;i<n-2;i++){
int left=i+1,right=n-1;
int ntarget=target-nums[i];
while(left<right){
int cur=nums[left]+nums[right];
if(abs(cur-ntarget)<diff){
diff=abs(cur-ntarget);
sum=cur+nums[i];
}
if(cur==ntarget) return target;
else if(cur<ntarget) left++;
else right--;
}
}
return sum;
}
};