给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出如今序列中的那个数。数组
示例 1:post
输入: [3,0,1]
输出: 2
复制代码
示例 2:spa
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
复制代码
本体的思路同「leetcode」136.只出现一次的数字基本相似,在一个0~n的连续数组中,缺乏一位。咱们在原有数组的基础上,填充一份等长的数组,而后依次对数组中的每个成员使用异或操做符,步骤拆解以下:code
nums = [a, b, d] a~d的连续数组中,缺乏cleetcode
nums = [a, b, d, a, b, c, d] 在原有数组中填充一份0~n连续完整的数组get
使用异或^, 处理数组中每个数字 a ^ b ^ d ^ a ^ b ^ c ^ dio
a ^ b ^ d ^ a ^ b ^ c ^ d 等价于 (a ^ a) ^ (b ^ b) ^ (d ^ d) ^ c 等价于 0 ^ 0 ^ 0 ^ c => cfunction
获得缺乏的数字cclass
/** * @param {number[]} nums * @return {number} */
var missingNumber = function(nums) {
let len = nums.length + 1
let result = 0
for (let i = 0; i < len; i++) {
nums.push(i)
}
for (let i = 0; i < nums.length; i++) {
result = nums[i] ^ result
}
return result
};
复制代码