和之前的3Sum一樣,隻是等于0換成了求最小差距, 加個cha即可,記得是絕對值!
int threeSumClosest(vector<int>& nums, int target)
{
int i,n,ans,left,right,num1,num2,num3,sum,cha;
n=nums.size();
sort(nums.begin(),nums.end());
ans=99999999;
for(i=0;i<n;i++)
{
num1=nums[i];
left=i+1;
right=n-1;
while(left<right)
{
num2=nums[left];
num3=nums[right];
sum=num1+num2+num3;
if(sum-target>0)
right--;
else if(sum-target<0)
left++;
else if(sum-target==0)
return sum;
cha=sum-target;
if(abs(cha)<abs(ans))
ans=cha;
}
}
return ans+target;
}