您的位置:首页 > 其它

【LeetCode】3Sum Closest

2014-04-16 22:50 302 查看
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,不再赘述。

class Solution {
public:

int Absolute_value(int x){
if(x<0)return -x;
return x;
}
int threeSumClosest(vector<int> &num, int target){
int nsize=num.size(),sum=0;
if(nsize<3){
for(nsize--;nsize>=0;nsize--)sum+=num[nsize];
return sum;
}
sum=num[0]+num[1]+num[2];
sort(num.begin(),num.end());
int i,j,k=nsize-1,tmp;
for(i=0;i<nsize-2;i++){
if(i > 0 && num[i]==num[i-1])
continue;
j=i+1;
k=nsize-1;
for(;j<k;){
tmp=num[j]+num[k]+num[i];
if(Absolute_value(sum-target)>Absolute_value(tmp-target))sum=tmp;
if(j>i+1&&num[j]==num[j-1]){
j++;
continue;
}
if(k<num.size()-1&& num[k]==num[k+1]){
k--;
continue;
}
if(num[j]+num[k]+num[i]>target)k--;
else if(num[j]+num[k]+num[i]<target)j++;
if(sum==target)return sum;
}
}
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: