您的位置:首页 > 其它

[leetcode] 3Sum Closest

2014-04-26 11:28 337 查看
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类似,但并不是列出所有和为0的三元组,而是找出与target最相近的sum,同样是利用三个指针i,p和q,具体请参考3Sum。只不过在遍历时记录最小误差minerror,最后返回target+minerror即可。

代码如下:

class Solution {
public:
int threeSumClosest(vector<int> &num, int target)
{
sort(num.begin(), num.end());
int minerror = num[0]+num[1]+num[2] - target;
for( int i = 0 ; i < num.size() ; i++ )
{
if( i > 0 && num[i] == num[i-1] )
{
continue;
}
int p = i+1;
int q = num.size() - 1;
while( p < q )
{
if( p > i +1 && num[p] == num[p-1] )
{
p++;
continue;
}

if( q < num.size() -1 &&  num[q] == num[q+1] )
{
q--;
continue;
}

int sum = num[i] + num[p] + num[q];

if( abs(sum - target) < abs(minerror) )
{
minerror = sum - target;
}

if( sum - target  == 0)
{
return target;
}

if( sum - target > 0 )
{
q--;
}

if( sum - target < 0 )
{
p++;
}
}
}
return minerror + target;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: