Skip to content

Commit d20099a

Browse files
add problem 41 and test function
1 parent 0dfbe3e commit d20099a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

C/1-50/41-First-Missing-Positive.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Given an unsorted integer array, find the first missing positive integer.
3+
4+
* For example,
5+
* Given [1,2,0] return 3,
6+
* and [3,4,-1,1] return 2.
7+
8+
* Your algorithm should run in O(n) time and uses constant space.
9+
* Created by supercoderx on 2017/8/13.
10+
*/
11+
#include
12+
13+
int firstMissingPositive(int *nums, int numsSize) {
14+
int tmp;
15+
for (int i = 0; i < numsSize; ++i) {
16+
while (nums[i] > 0 && nums[i] <= numsSize && nums[nums[i] - 1] != nums[i]) {
17+
tmp = nums[i];
18+
nums[i] = nums[tmp - 1];
19+
nums[tmp - 1] = tmp;
20+
}
21+
}
22+
for (int j = 0; j < numsSize; ++j) {
23+
if (nums[j] != j + 1)
24+
return j + 1;
25+
}
26+
return numsSize + 1;
27+
}
28+
29+
void testFirstMissingPositive() {
30+
int a[] = {2, 1};
31+
printf("%d", firstMissingPositive(a, 2));
32+
}

0 commit comments

Comments
 (0)