Skip to content

Commit b079580

Browse files
aQuaaQua
aQua
authored and
aQua
committed
通过测试
1 parent 56faf57 commit b079580

File tree

3 files changed

+62
-7
lines changed

3 files changed

+62
-7
lines changed

Algorithms/0041.first-missing-positive/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
11
# [41. First Missing Positive](https://leetcode.com/problems/first-missing-positive/)
22

33
## 题目
4+
Given an unsorted integer array, find the first missing positive integer.
45

6+
For example,
7+
```
8+
Given [1,2,0] return 3,
9+
and [3,4,-1,1] return 2.
10+
```
11+
Your algorithm should run in O(n) time and uses constant space.
512

613
## 解题思路
714

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,30 @@
11
package Problem0041
22

3+
import "sort"
4+
5+
func firstMissingPositive(nums []int) int {
6+
if len(nums) == 0 {
7+
return 1
8+
}
9+
10+
sort.Ints(nums)
11+
i := sort.SearchInts(nums, 0)
12+
if nums[i] == 0 {
13+
i++
14+
}
15+
16+
res := 1
17+
for i < len(nums) {
18+
if 0 < i && nums[i] == nums[i-1] {
19+
i++
20+
continue
21+
}
22+
if nums[i] != res {
23+
return res
24+
}
25+
i++
26+
res++
27+
}
28+
29+
return res
30+
}
Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0041
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,13 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one []int
1919
}
2020

2121
// ans 是答案
2222
// one 代表第一个答案
2323
type ans struct {
24-
one string
24+
one int
2525
}
2626

2727
func Test_Problem0041(t *testing.T) {
@@ -30,17 +30,37 @@ func Test_Problem0041(t *testing.T) {
3030
qs := []question{
3131

3232
question{
33-
para{""},
34-
ans{""},
33+
para{[]int{1}},
34+
ans{2},
35+
},
36+
37+
question{
38+
para{[]int{0, 2, 2, 1, 1}},
39+
ans{3},
40+
},
41+
42+
question{
43+
para{[]int{}},
44+
ans{1},
3545
},
36-
46+
47+
question{
48+
para{[]int{1, 2, 0}},
49+
ans{3},
50+
},
51+
52+
question{
53+
para{[]int{3, 4, -1, 1}},
54+
ans{2},
55+
},
56+
3757
// 如需多个测试,可以复制上方元素。
3858
}
3959

4060
for _, q := range qs {
4161
a, p := q.ans, q.para
4262
fmt.Printf("~~%v~~\n", p)
4363

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
64+
ast.Equal(a.one, firstMissingPositive(p.one), "输入:%v", p)
4565
}
4666
}

0 commit comments

Comments
 (0)