美文网首页LeetCode By Go
[LeetCode By Go 57]268. Missing

[LeetCode By Go 57]268. Missing

作者: miltonsun | 来源:发表于2017-08-23 17:55 被阅读6次

题目

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
}

相关文章

网友评论

    本文标题:[LeetCode By Go 57]268. Missing

    本文链接:https://www.haomeiwen.com/subject/hxljdxtx.html