[LeetCode By Go 57]268. Missing Number

题目

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?

解题思路

  1. 申请一个len(nums)+1长度的数组numArr,nums中有的值i 将numArr[i]置为true
  2. 遍历数组,找到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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容