缺失数字
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
Python代码
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxnum = max(nums)
for i in range(maxnum+1):
if i not in nums:
return i
return maxnum + 1
执行用时 : 2692 ms, 在Missing Number的Python提交中击败了6.22% 的用户
内存消耗 : 12.8 MB, 在Missing Number的Python提交中击败了7.84% 的用户
Python一行实现,主要思路是求和,然后等差数列前n项和对比,做差即是答案。(应用等差数列求和公式)
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return len(nums) * (len(nums) + 1)/2 - sum(nums)
执行用时 : 164 ms, 在Missing Number的Python提交中击败了28.77% 的用户
内存消耗 : 12.6 MB, 在Missing Number的Python提交中击败了21.18% 的用户