Given an array containing n distinctnumbers taken from 0, 1, 2, ..., n, find the one that is missing fromthe array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement itusing only constant extra space complexity?
要找出0到n这个序列中哪个数字缺失,可以用序列中所有值的和减去序列中其他数值的和得到。
比如序列为[0 1 2 4]
序列的和为7,序列 [0,1,2,3,4] 的和为10.
10减7得到3,即为缺失的值。
这里假设只缺失一个值,所以这种方法可行。
Python代码如下
def missingNumber(self, nums): l=len(nums) s= int(l*(l+1)/2) sn=0 for i in nums: sn+=i return s-sn
a=[0,1,2,3,4,6,7] #expected 5 b=[0] #expected 1 c=[1,0] #expected 2 self=0 print(missingNumber(self,a)) |
说明:l为输入序列的长度,先求出 0到l 的序列和,再求出nums中数的和,相减即得到不在序列中的那一个。