今日全天解决问题去了,时间到了,先简单转载提交,马上自己做试试.
int cmp(const void * a, const void * b)
{
return * (int * )a - * (int * )b;
}
int abs(int x)
{
if (x > 0) {
return x;
} else {
return -x;
}
}
int threeSumClosest(int* nums, int numsSize, int target)
{
qsort(nums, numsSize, sizeof(int), cmp);
int result = nums[0] + nums[1] + nums[2];
for (int i = 0; i < numsSize - 2; i++) {
int l = i + 1;
int r = numsSize - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (abs(sum - target) < abs(result - target)) {
result = sum;
}
if (sum < target) {
l++;
} else if (sum > target) {
r--;
} else {
return result;
}
}
}
return result;
}