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).
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int len = nums.size();
int mindist = 99999;
int cur = 0;
int ret = 0;
int dist = 0;
int curdist = 0;
for(int i=0; i<len; ++i)
{
int front = i + 1;
int back = len - 1;
while(front<back)
{
cur = nums[i] + nums[front] + nums[back];
dist = cur - target;
curdist = dist<=0? -dist:dist;
if(curdist<mindist)
{
mindist = curdist;
ret = cur;
}
if(front<back && dist<0)
{
++front;
}
else if(front<back && dist>0)
{
--back;
}
else if(front<back && dist==0)
{
ret = cur;
return ret;
}
}
}
return ret;
}
};