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) {
sort(num.begin(),num.end());
int closet = num[]+num[]+num[];
for(int i = ; i < num.size()-; ++ i){
int start = i+, end = num.size()-,sum = ;
while(start < end){
sum = num[i] + num[start] + num[end];
if(sum == target) return sum;
else if(sum > target) end--;
else start++;
closet = abs(sum - target) < abs(closet-target) ? sum : closet;
}
}
return closet;
}
};