268.丢失的信息(javascript)268.MissingNumber
原创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.
首先是解决问题的想法。
分析主题:
步骤1:首先对获取的数组进行排序
第二部分:当索引值对应的值与索引值不匹配时,将返回当前索引,即缺少的值。
步骤3:未发现差异,数组的长度是缺少的值。
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
};
解决问题的第二个想法
步骤1:首先将数组的所有项添加到哈希集合中,
第二部分,遍历[0,nums.length]-这包含0和nums.length
第3步:在这个范围内查找,而不是在哈希集合中,然后返回它。
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
}
}
}; 版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123




