先排序,然后左右夹逼,
每次当sum-target < diff 用diff记录下最小距离
static int intcmp(const void *a, const void *b)
{
return(*(int *)a - *(int *)b);
}
int threeSumClosest(int* nums, int numsSize, int target) {
qsort(nums, numsSize, sizeof(nums[0]), intcmp);
int res=0, sum=0, diff=2147483647, start, end;
for(int i=0; i<=numsSize-3;i++)
{
if(i>0 && nums[i]==nums[i-1])
continue;
start = i+1;
end = numsSize-1;
while(start<end)
{
sum = nums[i] + nums[start] + nums[end];
if(sum<target){
if(target-sum < diff)
{
diff = target-sum;
res = sum;
}
start++;
}
else if(sum>target){
if(sum-target < diff)
{
diff = sum-target;
res = sum;
}
end--;
}
else
return sum;
}
}
return res;
}
网友评论