题目描述:给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。
样例:N = 4 且序列为 [0, 1, 3] 时,缺失的数为2。
之前,有一道找寻第一个丢失的正整数(详见:点击打开链接)的问题。当时用的是桶排序(详见:点击打开链接)
这题题呢,其实和上一道题没有本质不同了,完全可以用相同的方法解决。但是更简单,为什么呢?因为所有数组中可能出现的元素的范围已经确定了。
但是桶排序的方法就这道题本身而言,有点“杀鸡用牛刀”了,完全不用那么复杂。
因为数组缺失的数肯定是0-N中的一个,而数组所有的元素都是0-N中,除了缺失的数之外的其他数构成的。所以最简单的思路是对数组求和,再根据等差数列的求和公式对0-N求和,后面的和减去前面的和就行。
代码如下:
class Solution:
# @param nums: a list of integers
# @return: an integer
def findMissing(self, nums):
n = len(nums)
i = 0
sum_value = 0
while i != n:
sum_value += nums[i]
i += 1
return n * (n + 1) / 2 - sum_value
# write your code here
如果不用数学的方法,循环也能解决:
class Solution:
# @param nums: a list of integers
# @return: an integer
def findMissing(self, nums):
n = len(nums)
i = 0
sum_value = 0
while i != n:
sum_value -= nums[i]
sum_value += i
i += 1
return sum_value + n
# write your code here
算的东西结果是一样的。