题目:
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).
思路:
类似
http://blog.csdn.net/lanxu_yy/article/details/11896109。
代码:
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num.size() < 3)
{
return INT_MIN;
}
int min = INT_MAX;
sort(num.begin(), num.end());
for(int i = 0; i < num.size()-2; i++)
{
if(i > 0 && num[i] == num[i-1])
{
continue;
}
for(int j = i+1; j < num.size()-1; j++)
{
if(j > i+1 && num[j] == num[j-1])
{
continue;
}
int left = j+1;
int right = num.size()-1;
while(left<=right)
{
int mid = left + ((right-left)>>1);
if(num[i] + num[j] + num[mid] == target)
{
return target;
}
else if(num[i] + num[j] + num[mid] > target)
{
int m = num[i] + num[j] + num[mid];
if(min == INT_MAX)
{
min = m;
}
else
{
min = abs(m-target)<abs(min-target)?m:min;
}
right = mid - 1;
}
else
{
int m = num[i] + num[j] + num[mid];
if(min == INT_MAX)
{
min = m;
}
else
{
min = abs(m-target)<abs(min-target)?m:min;
}
left = mid + 1;
}
};
}
}
return min;
}
};