Skip to content

Commit

Permalink
Three sum closest
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 26, 2017
1 parent f61316c commit 3f10471
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 016_three_sum_closest/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test three_sum_closest.c -lm
53 changes: 53 additions & 0 deletions 016_three_sum_closest/three_sum_closest.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

static void insert_sort(int *a, int size)
{
int i, j;
for (i = 1; i < size; i++) {
int tmp = a[i];
for (j = i - 1; j >= 0 && a[j] > tmp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = tmp;
}
}

static int threeSumClosest(int* nums, int numsSize, int target) {
int i, min_diff = INT_MAX;

if (numsSize < 3) {
return min_diff;
}

insert_sort(nums, numsSize);

for (i = 0; i < numsSize - 2; i++) {
int left = i + 1;
int right = numsSize - 1;
while (left < right) {
int diff = nums[i] + nums[left] + nums[right] - target;
if (abs(diff) < abs(min_diff)) {
min_diff = diff;
}
if (diff < 0) {
left++;
} else if (diff > 0) {
right--;
} else {
break;
}
}
}
return min_diff + target;
}

int main(void)
{
int i, target = 1;
int nums[] = { -1, 2, 1, -4 };
printf("%d\n", threeSumClosest(nums, sizeof(nums) / sizeof(nums[0]), target));
return 0;
}

0 comments on commit 3f10471

Please sign in to comment.