算法,写代码

leetcode 268 Missing Number

2017-10-06  本文已影响0人  小双2510

原题是:

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函数。

上一篇下一篇

猜你喜欢

热点阅读