Skip to content

Commit

Permalink
First missing positive
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 29, 2017
1 parent e39d469 commit 8d7c8b0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 041_first_missing_positive/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test missing_positive.c
40 changes: 40 additions & 0 deletions 041_first_missing_positive/missing_positive.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>

static void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}

static int firstMissingPositive(int* nums, int numsSize) {
if (numsSize < 1) {
return 1;
}

int i = 0;
while (i < numsSize) {
if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= numsSize && nums[i] != nums[nums[i] - 1]) {
swap(nums + i, nums + nums[i] - 1);
} else {
i++;
}
}

for (i = 0; i < numsSize; i++) {
if (nums[i] != i + 1) break;
}
return i + 1;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
printf("%d\n", firstMissingPositive(nums, count));
return 0;
}

0 comments on commit 8d7c8b0

Please sign in to comment.