美文网首页
Leetcode_268 Missing Number

Leetcode_268 Missing Number

作者: vcancy | 来源:发表于2018-04-20 16:26 被阅读0次

给出一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。

案例 1

输入: [3,0,1]
输出: 2

案例 2

输入: [9,6,4,2,3,5,7,0,1]
输出: 8

注意事项:
您的算法应该以线性复杂度运行。你能否仅使用恒定的额外空间复杂度来实现它?

"""

数学:
前n项和公式a1n+n(n-1)/2,减去nums里面的所有数即是缺失的数

"""

class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)+1
        total = n*(n-1)/2
        for i in nums:
            total -=i
        return int(total)

相关文章

网友评论

      本文标题:Leetcode_268 Missing Number

      本文链接:https://www.haomeiwen.com/subject/ghkzkftx.html