1. 程式人生 > >【python3】leetcode 268. Missing Number (easy)

【python3】leetcode 268. Missing Number (easy)

 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