- 题目
数组nums包含从0到n的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗?
- 示例1
输入:[3,0,1]
输出:2
- 示例2
输入:[9,6,4,2,3,5,7,0,1]
输出:8
- 题解1
var missingNumber = function(nums) {
nums.sort((a,b)=>a-b)
let len =nums.length
for (let i in nums){
if(Number(i)!==nums[i]){
return i
}
}
return len
}
- 题解2
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
const n = nums.length;
const sum = (n + 1) * n / 2;
const arrSum = nums.reduce((pre, cur) => {
return pre + cur;
});
return sum - arrSum;
};
来源:力扣
原题链接:https://leetcode-cn.com/problems/missing-number-lcci/submissions/