feat: add solution for the 3Sum Closest problem (#16) (#1216)

* feat: add solution for the 3Sum Closest problem (#16)

* fix: Update formatting

* fix: update compare function to avoid overflow in generic case

* chore: apply suggestions from code review

---------

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Mindaugas 2023-02-21 10:55:09 +00:00 committed by GitHub
parent 5bf2c42bff
commit 5d3a841aa6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -18,6 +18,7 @@
| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman) | [C](./src/12.c) | Medium |
| 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer) | [C](./src/13.c) | Easy |
| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix) | [C](./src/14.c) | Easy |
| 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest) | [C](./src/16.c) | Medium |
| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses) | [C](./src/20.c) | Easy |
| 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists) | [C](./src/21.c) | Easy |
| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs) | [C](./src/24.c) | Medium |

30
leetcode/src/16.c Normal file
View File

@ -0,0 +1,30 @@
#include <stdlib.h> // for qsort()
int cmp(const void* a, const void* b) {
const int *A = a, *B = b;
return (*A > *B) - (*A < *B);
}
int threeSumClosest(int* nums, int nums_size, int target) {
int i, j, k, result, sum3;
qsort(nums, nums_size, sizeof(int), cmp);
result = nums[0] + nums[1] + nums[2];
for (i = 0; i < nums_size - 2; i++) {
j = i + 1;
k = nums_size - 1;
while (j < k) {
sum3 = nums[i] + nums[j] + nums[k];
if (abs(target - sum3) < abs(target - result)) {
result = sum3;
}
if (sum3 < target) {
j++;
} else if (sum3 > target) {
k--;
} else {
return sum3;
}
}
}
return result;
}