Missing digits from 0 to n-1

0x00

无聊写写题

0x01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

/**
一个长度为 n-1 的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围 0~n-1 之内。
在范围 0~n-1 内的 n 个数字中有且只有一个数字不在该数组中,请找出这个数字。

示例 1:

输入: [0,1,3]
输出: 2
示例 2:

输入: [0,1,2,3,4,5,6,7,9]
输出: 8

*/

// 直观思维
func missingNumber(nums []int) int {
if nums[0] != 0 {
return 0
}
for i := 1; i < len(nums); i++ {
if nums[i]-nums[i-1] == 2 {
return nums[i] - 1
}
}
return len(nums)
}

// nums[i] == i 遍历思路
func missingNumber1(nums []int) int {
for i := 0; i < len(nums); i++ {
if nums[i] != i {
return i
}
}
return len(nums)
}

// 二分查找
func missingNumber2(nums []int) int {
left, right := 0, len(nums)-1
for left <= right {
m := left + (right-left)/2
if nums[m] == m { // 说明在右半部分
left = m + 1
} else {
right = m - 1
}
}
return left
}
  • 单元测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
"testing"

"github.com/bmizerany/assert"
)

func TestMissNumber(t *testing.T) {
t.Run("首", func(t *testing.T) {
m := missingNumber([]int{1, 2, 3})
assert.Equal(t, 0, m, 0)
})
t.Run("尾", func(t *testing.T) {
m := missingNumber([]int{0, 1, 2})
assert.Equal(t, 3, m, 3)
})
t.Run("中间", func(t *testing.T) {
m := missingNumber([]int{0, 1, 3})
assert.Equal(t, 2, m, 2)
})
}

func TestMissNumber1(t *testing.T) {
t.Run("首", func(t *testing.T) {
m := missingNumber1([]int{1, 2, 3})
assert.Equal(t, 0, m, 0)
})
t.Run("尾", func(t *testing.T) {
m := missingNumber1([]int{0, 1, 2})
assert.Equal(t, 3, m, 3)
})
t.Run("中间", func(t *testing.T) {
m := missingNumber1([]int{0, 1, 3})
assert.Equal(t, 2, m, 2)
})
}

func TestMissNumber2(t *testing.T) {
t.Run("首", func(t *testing.T) {
m := missingNumber2([]int{1, 2, 3})
assert.Equal(t, 0, m, 0)
})
t.Run("尾", func(t *testing.T) {
m := missingNumber2([]int{0, 1, 2})
assert.Equal(t, 3, m, 3)
})
t.Run("中间", func(t *testing.T) {
m := missingNumber2([]int{0, 1, 3})
assert.Equal(t, 2, m, 2)
})
}

代码已托管 algorithm-coding

0x02

Author: ronething
Link: https://blog.ronething.cn/20200912-algo.html
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.