【leetcode】3Sum Closest

3Sum Closest

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类似,只是需要添加一个变量distance,用来记录和target距离最小的a+b+c
 
 class Solution {
public:
int threeSumClosest(vector<int> &num, int target) { int n=num.size();
sort(num.begin(),num.end()); int i,j,k;
int a,b,c;
int result;
int distance=INT_MAX; for(i=;i<n-;i++)
{
j=i+;
k=n-; while(j<k)
{
a=num[i];
if(i>&&num[i]==num[i-])
{
break;
}
b=num[j];
if(j>i+&&num[j]==num[j-])
{
j++;
continue;
} c=num[k];
if(k<n-&&num[k]==num[k+])
{
k--;
continue;
} if(a+b+c==target)
{
return target;
}
else if(a+b+c<target)
{
if(target-(a+b+c)<distance)
{
result=a+b+c;
distance=target-result;
}
j++;
}
else if(a+b+c>target)
{
if((a+b+c)-target<distance)
{
result=a+b+c;
distance=result-target;
}
k--;
}
}
} return result; }
};
上一篇:CM+CDH安装遇到的问题


下一篇:我的屌丝giser成长记-研一篇(下)