[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
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/af0116763b15
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞