C代码
#define VALUE(ptr) (*((int *)ptr))
#define MIN_ONE(a, b) ((a)>(b)?(b):(a))
int comp(const void *a, const void *b) {
return VALUE(a) - VALUE(b);
}
int threeSumClosest(int* nums, int numsSize, int target){
int i,j,k;
int min = 0x7fffffff;
int oldmin = min;
int sum = 0;
int sign = 1;
qsort(nums, numsSize, sizeof(int), comp);
for(i = 0; i < numsSize - 2; i++) {
j = i + 1;
k = numsSize - 1;
while(j < k) {
sum = nums[i] + nums[j] + nums[k];
oldmin = min;
min = MIN_ONE(min, (sum - target) > 0 ? sum - target : target - sum);
if (oldmin != min) {
sign = sum;
}
if(sum > target) {
k--;
continue;
}
if (sum < target) {
j++;
continue;
}
return sum;
}
}
return sign;
}
结果
注意点
j
与k
的判断,曾写错为j>k