题目
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
解题思路
- 申请一个len(nums)+1长度的数组numArr,nums中有的值i 将numArr[i]置为true
- 遍历数组,找到numArr[j]为false,则j即为要求的值
代码
func missingNumber(nums []int) int {
len1 := len(nums)
var numArr []bool
numArr = make([]bool, len1 + 1)
for i := 0; i < len1; i++ {
numArr[nums[i]] = true
}
var ret int
for k, v := range numArr {
if false == v {
ret = k
}
}
return ret
}