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).
排序是必须的,与3sum问题不同。不需要进行去重。采用二分搜索的方法,必须要进行大小判定以确定前后下标的移动。
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int n=num.size();
int i=0,j,k;
sort(num.begin(),num.end());
int sum1=num[0]+num[1]+num[2]-target;
int sum2=0;
while(i<n){
for(j=i+1,k=n-1;j<k;){
sum2=num[i]+num[j]+num[k]-target;
if(fabs(sum2)<fabs(sum1)) sum1=sum2;
if(sum2>0){
k--;
}else{
j++;
}
}
i++;
}
return sum1+target;
}
};