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.
没啥fancy的,sort完事了就行了。。。本来还想优化的,和3sum一样整一遍完事了。。。
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
sort(num.begin(),num.end());
int size=num.size();
int res=num[0]+num[1]+num[size-1];
for (int i=0; i<size;i++){
int begin=i+1;
int end=size-1;
while(begin<end){
int sum=num[i]+num[begin]+num[end];
if (abs(target-sum)<abs(target-res)){
res=sum;
}
if (sum==target)
return sum;
if (sum>target)
end--;
if (sum<target)
begin++;
}
}
return res;
}
};