File tree Expand file tree Collapse file tree 1 file changed +25
-22
lines changed
solution/0000-0099/0016.3Sum Closest Expand file tree Collapse file tree 1 file changed +25
-22
lines changed Original file line number Diff line number Diff line change @@ -317,30 +317,33 @@ class Solution {
317317
318318#### C
319319
320- ``` C
321- int cmp (const void * a, const void * b) { return * (int * )a - * (int * )b; }
322-
323- int threeSumClosest(int * nums, int numsSize, int target) {
324- qsort(nums, numsSize, sizeof(int), cmp);
325- int closest = nums[ 0] + nums[ 1] + nums[ 2] ;
326-
327- for (int i = 0; i < numsSize - 2; i++) {
328- int j = i + 1, k = numsSize - 1;
329- while (j < k) {
330- int sum = nums[ i] + nums[ j] + nums[ k] ;
331- if (abs(sum - target) < abs(closest - target)) {
332- closest = sum;
333- }
334- if (sum < target)
335- j++;
336- else
337- k--;
338- }
339- }
340-
341- return closest;
320+ ``` c
321+ int cmp (const void* a, const void* b) {
322+ return (* (int* ) a - * (int* ) b);
342323}
343324
325+ int threeSumClosest(int* nums, int numsSize, int target) {
326+ qsort(nums, numsSize, sizeof(int), cmp);
327+ int ans = 1 << 30;
328+ for (int i = 0; i < numsSize; ++i) {
329+ int j = i + 1, k = numsSize - 1;
330+ while (j < k) {
331+ int t = nums[ i] + nums[ j] + nums[ k] ;
332+ if (t == target) {
333+ return t;
334+ }
335+ if (abs(t - target) < abs(ans - target)) {
336+ ans = t;
337+ }
338+ if (t > target) {
339+ --k;
340+ } else {
341+ ++j;
342+ }
343+ }
344+ }
345+ return ans;
346+ }
344347```
345348
346349<!-- tabs:end -->
You can’t perform that action at this time.
0 commit comments