Skip to content

Commit 5206a26

Browse files
committed
solution for the first missing positive
1 parent c20184f commit 5206a26

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// https://leetcode.com/submissions/detail/445082440/
2+
3+
package main
4+
5+
func firstMissingPositive(nums []int) int {
6+
sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
7+
8+
expectedNum := 1
9+
for i := 0; i < len(nums); i++ {
10+
if nums[i] <= 0 {
11+
continue
12+
}
13+
14+
if nums[i] != expectedNum {
15+
break
16+
}
17+
18+
for ; i < len(nums) && nums[i] == expectedNum; i++ {
19+
}
20+
i--
21+
expectedNum++
22+
}
23+
24+
return expectedNum
25+
}
26+
27+
// 1, 2, 0 -> 0, 1, 2
28+
// n=0, exp=0, c; n=1, exp=0, exp=2(n+1), c; n=2, exp=2, exp=3(++); c; eoc; ret exp(3)
29+
30+
// 3, 4, -1, 1 -> -1, 1, 3, 4 -> 1
31+
// n=-1, c; n=1, exp=2; n=3, exp=2, break; return exp(2)
32+
33+
// Trivial:
34+
// 1. sort - N*logN CPU, O(N) - space complexity for merge sort, qsort
35+
// 2. iterate - find first positive, after that find first missing positive
36+
37+
// Test cases
38+
// 1. simple: [0, 1, 2, 3, 5], [34, 36, 50], [-50, -30, -3, -2, -1, 0, 1, 2, 3, 5]
39+
// 2. missing two or more positives: [0, 1, 2, 3, 5, 8, 12]
40+
// 3. no-zero: [[1, 2, 3, 5]]
41+
// 4. no-zero and negatives: [-1, -2, -4, 1, 2, 3, 5]
42+
// 5. empty: []
43+
// 6. no-positives: [-5, -4, -3, -2, -1]
44+
// 7. no-positives and zero: [-5, -4, -3, -2, -1, 0]
45+
// 8. no-positives, zero and missing negatives: [-10, -8, -5, -4, -3, -2, -1, 0]
46+
// 9. no missing positives: 2^31-1 [1<<31-3, 1<<31-2, 1<<31-1] -> [2147483645, 2147483646, 2147483647]
47+
// 10. [0]
48+
// 11. [1]
49+
// 12. [2]
50+
// 13. [-2]
51+
// 14. Repeatable: [0,2,2,1,1]

0 commit comments

Comments
 (0)