#define INT_MAX 2147483647 int cmp(const void* a, const void* b){ return *(int*)a - *(int*)b; // 快排构造递增序列 } int threeSumClosest(int* nums, int numsSize, int target){ int cur=0; int left = cur + 1, right = numsSize - 1, minVal = INT_MAX, ret=0, temp; qsort(nums, numsSize, sizeof(int), cmp); while (cur < numsSize - 2){ left = cur + 1; right = numsSize - 1; while (left < right){ temp = nums[cur] + nums[left] + nums[right]; if (abs( temp - target) < minVal){ minVal = abs(temp - target); ret = temp; } if (temp == target) return temp; else if (temp < target){ while (nums[left] == nums[++left] && left < right); } else{ while (nums[right] == nums[--right] && left < right); } } while (nums[cur] == nums[++cur] && cur < numsSize - 2); } return ret; }