// similar to threeSum
int threeSumClosest(vector<int> &num, int target) {
if(num.size()<3)
return 0;
sort(num.begin(),num.end());
int ret=num[0]+num[1]+num[2];
for (int i=0;i<num.size()-2;i++)
{
// remove duplicates
if(i>0&&num[i]==num[i-1])
continue;
int start=i+1;
int end=num.size()-1;
while(start<end)
{
int sum=num[i]+num[start]+num[end];
if(abs(sum-target)<abs(ret-target))
{
ret=sum;
}
if(sum>target)
{
end--;
}
else if(sum<target)
{
start++;
}
else
{
return target;
}
}
}
return ret;
}
No comments:
Post a Comment