diff --git a/041_first_missing_positive/Makefile b/041_first_missing_positive/Makefile new file mode 100644 index 0000000..4c24d01 --- /dev/null +++ b/041_first_missing_positive/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test missing_positive.c diff --git a/041_first_missing_positive/missing_positive.c b/041_first_missing_positive/missing_positive.c new file mode 100644 index 0000000..4e23b3f --- /dev/null +++ b/041_first_missing_positive/missing_positive.c @@ -0,0 +1,40 @@ +#include +#include + +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; +}