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 @@ -316,30 +316,33 @@ class Solution {
316
316
317
317
#### C
318
318
319
- ``` C
320
- int cmp (const void * a, const void * b) { return * (int * )a - * (int * )b; }
321
-
322
- int threeSumClosest(int * nums, int numsSize, int target) {
323
- qsort(nums, numsSize, sizeof(int), cmp);
324
- int closest = nums[ 0] + nums[ 1] + nums[ 2] ;
325
-
326
- for (int i = 0; i < numsSize - 2; i++) {
327
- int j = i + 1, k = numsSize - 1;
328
- while (j < k) {
329
- int sum = nums[ i] + nums[ j] + nums[ k] ;
330
- if (abs(sum - target) < abs(closest - target)) {
331
- closest = sum;
332
- }
333
- if (sum < target)
334
- j++;
335
- else
336
- k--;
337
- }
338
- }
339
-
340
- return closest;
319
+ ``` c
320
+ int cmp (const void* a, const void* b) {
321
+ return (* (int* ) a - * (int* ) b);
341
322
}
342
323
324
+ int threeSumClosest(int* nums, int numsSize, int target) {
325
+ qsort(nums, numsSize, sizeof(int), cmp);
326
+ int ans = 1 << 30;
327
+ for (int i = 0; i < numsSize; ++i) {
328
+ int j = i + 1, k = numsSize - 1;
329
+ while (j < k) {
330
+ int t = nums[ i] + nums[ j] + nums[ k] ;
331
+ if (t == target) {
332
+ return t;
333
+ }
334
+ if (abs(t - target) < abs(ans - target)) {
335
+ ans = t;
336
+ }
337
+ if (t > target) {
338
+ --k;
339
+ } else {
340
+ ++j;
341
+ }
342
+ }
343
+ }
344
+ return ans;
345
+ }
343
346
```
344
347
345
348
<!-- tabs:end -->
You can’t perform that action at this time.
0 commit comments