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?
根据题意,给一个list,没有重复数字,从0开始到n。但是中间有一个数字不见了。需要找到并输出这个数字。
很简单的两种方法
class Solution(object):
def missingNumber(self, nums):
return (set(range(len(nums)+1)) - set(nums)).pop()
利用set的bit操作,剩下的就是我们需要的missing number
class Solution(object):
def missingNumber(self, nums):
return (len(nums) + 1) * len(nums) / 2 - sum(nums)
利用的是数学的求和公式,0~n,和就是((N+1)*N)/2, 然后减去给定的list,就能找到missing number。
题目的提示的bit manipulation,我们可以用异或XOR来得到结果。
class Solution(object):
def missingNumber(self, nums):
x = nums[0] # nums will be [0,1,2,..n] => nums[0] = 0
y = 0
for i in range(1, len(nums)):
x ^= nums[i] # XOR all numbers
y ^= i # same like above
y ^= len(nums) # one number is missing, means totally have len(nums) numbers
return x^y
因为,loop的值和index是一样的,都从0开始到n。但是因为有missing number,所以index是完全的0~n,而value值是缺少一个数字的。
所以最后index的异或和value值的异或,就会把missing number找到。