美文网首页算法,写代码
leetcode 268 Missing Number

leetcode 268 Missing Number

作者: 小双2510 | 来源:发表于2017-10-06 11:15 被阅读0次

原题是:

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

思路是:

求和,不缺数字时的和,减去缺一个数字的和,得到所缺的那个数字。

代码是:

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

借鉴别人代码:

def missingNumber(self, nums):
    n = len(nums)
    return n * (n+1) / 2 - sum(nums)

用了Python内置的sum函数。

相关文章

网友评论

    本文标题:leetcode 268 Missing Number

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