题目:
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.
给定一个含有n个整数的数列,找出三个数,使得它们三个的和与给定的数target的差值的距离最小。返回符合条件的三个数的和。你可以假定每个输入都有一个结果。
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/u012243115/article/details/41361781
代码:
class Solution {
public:
int threeSumClosest(vector<int> &num, int target)
{
int pre = 0x7fffffff;
int result = 0;//保存三个数的和
sort(num.begin(),num.end());//先对数组排序
int len = num.size();
if(len < 3)
return 0;
for(int i = 0 ; i < len ; i++)
{
if( i > 0 && num[i] == num[i-1])
{
continue;//如果重复,则跳到下一个,一定要结束本次循环,重新进行判断
}
for(int j = i + 1 , k = len - 1 ; j < k ; )
{
if(j > i+1 && num[j] == num[j-1])
{
j++;
continue;
}
if(k < len - 1 && num[k] == num[k+1])
{
k--;
continue;
}
int cur = num[i] + num[j] + num[k];
int gap = cur - target > 0 ? cur - target : target - cur;//差值
//如果差值比之前的小,则保存当前的三个数和到result
if(gap < pre)
{
pre = gap;
result = cur;
}
//判断当前三个数的和与target的大小,决定j和k的移动方向
if(cur < target)
j++;
else
k--;
}
}
return result;
}
};