【python3】leetcode 268. Missing Number (easy)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84976427

 268. Missing Number (easy)

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

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

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

注意有一个点:题目说一定存在一个缺失值,所以如果给定的nums本身无缺失值,比如[0,1,2,3 ],那么就是4缺失了。

1 我的思路(not fast,70-100ms

先排序后比较第i位是否是i

class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        if(nums[-1] == len(nums)-1):return len(nums)
        for i in range(len(nums)):
            if nums[i] != i:return i
        

2 从连续数字的特性入手(fast

0~n个连续数字的和是 n*(n+1) / 2

与nums的和相减就是缺失的数啦

class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        numsum = (len(nums) * (len(nums) + 1)) / 2
        return int(numsum - sum(nums))

Runtime: 44 ms, faster than 98.77% of Python3 

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84976427