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的变体,前后两个指针的O(n)变体。
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
//TODO input check
int ithreeclose=0;
if(target>=0)
ithreeclose=INT_MAX;
else
ithreeclose=INT_MIN;
sort(num.begin(),num.end() );
for(int i=0; i<num.size()-2; ++i)
{
int itwoclose=twoSumClosest(num,i+1,target-num[i]);
if(abs(itwoclose+num[i]-target) < abs(ithreeclose-target) )
{
ithreeclose = itwoclose+num[i];
}
}
return ithreeclose;
}
int twoSumClosest(vector<int>& num,int ibeg, int target)
{
int iclose=0;
if(target>=0)
iclose=INT_MAX;
else
iclose=INT_MIN;
int iend=num.size()-1;
while(ibeg < iend)
{
if(num[ibeg]+num[iend] == target)
//break;
return target;
else if(num[ibeg]+num[iend] < target)
{
if(abs(num[ibeg]+num[iend]-target) < abs(iclose-target) )
iclose = num[ibeg]+num[iend];
++ibeg;
}
else
{
if(abs(num[ibeg]+num[iend]-target) < abs(iclose-target) )
iclose = num[ibeg]+num[iend];
--iend;
}
}
return iclose;
}
};