题目:
缺失数字:给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
示例:
输入: [3,0,1], 输出: 2
输入: [9,6,4,2,3,5,7,0,1], 输出: 8
输入: [1], 输出: 0
输入: [0], 输出: 1
输入: [0,1], 输出: 2
说明: 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
----------------------------------------------------------------------------------------
解法1: 最常规做法, nums排序的sort()函数, 然后找位置插入
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1 and nums[-1] == 0:
return 1
if len(nums) >= 1 and 0 not in nums:
return 0
nums.sort()
for i in range(len(nums) - 1):
if nums[i + 1] - nums[i] == 2:
return nums[i] + 1
if len(nums) > 1 and nums[-1] - nums[-2] == 1:
return nums[-1] + 1
解法2:通过枚举法,sort()函数 + enumerate()函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
enumerate(sequence, [start=0])
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for key, value in enumerate(nums):
if key != value:
return key
else:
return key + 1
解法3:数学方法,等差数列的性质
思路:nums相当于一个等差数列减去某一个数, 所以用该等差数列的和减去nums的和即为所求。
等差数列求和公式:Sn = n*a1+n(n-1)d/2 或 Sn = n(a1+an)/2。
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# int(len(nums) * (len(nums)+1)/2 为等差数列的和
# sum(nums)为列表的的和
# 二者的差值即为缺失值
return (int(len(nums) * (len(nums)+1)/2) - sum(nums))
解法4:申请len(nums)+1长度的数组用于标记
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
checkList = [False] * (len(nums) + 1)
for i in nums:
checkList[i] = True
for i, j in enumerate(checkList):
if not j:
return i
解法5: 位运算
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
bit = 0
for i, j in enumerate(nums):
bit ^= i ^ j
return bit ^ len(nums)
解法6:set()函数
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (set(range(len(nums) + 1)) - set(nums)).pop()
参考:
https://www.runoob.com/python/python-func-enumerate.html
https://blog.youkuaiyun.com/qq_34364995/article/details/80699747
https://blog.youkuaiyun.com/qiubingcsdn/article/details/82913085