268. 丢失的数字(javascript)268. Missing Number

leetcode:https://leetcode-cn.com/problems/missing-number/
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

示例 1:

输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

示例 2:

输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。

Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

示例 3:

输入:nums = [9,6,4,2,3,5,7,0,1]
输出:8
解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。

示例 4:

输入:nums = [0]
输出:1
解释:n = 1,因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1 是丢失的数字,因为它没有出现在 nums 中。

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

第一种:解题思路

对题目进行解析:
第一步:先将获取的这个数组进行排序
第二部:当索引值对应的值与索引值不符时,返回当前索引,即缺失的值
第三步:未发现,不符项时,数组长度即为缺失的值

var missingNumber = function (nums) {
    nums.sort((a, b) => a - b)
    let nLen = nums.length
    for (let i = 0; i < nLen; i++) {
        if (nums[i] != i) {
            console.log("i", i);
            return i
        }
    }
    return nLen
};

第二种解题思路
第一步:先将数组所有项,添加到哈希集合,
第二部,遍历[0,nums.length]—此处包含0和nums.length
第三步:寻找在这个范围内,不在哈希集合中的,将其返回

var missingNumber = function (nums) {
    let newSet = new Set()
    let nlen = nums.length
    for (let i = 0; i < nlen; i++) {
        newSet.add(nums[i])
    }
    for (let i = 0; i <= nlen; i++) {
        if (!newSet.has(i)) {
            return i
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值