leetcode 268. Missing Number( Python )

348 阅读21分钟

描述

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?

解析

根据题意肯定用公式计算方法最快,就是把 M 中,每个位置上的数字变成它周围数字(包括自身)总和的平均数,如果是角落的或者边缘的数字,那就只计算若干个数字的平均值,时间复杂度为 O(N) ,公式计算为 O(1),但是求和过程为 O(N),空间复杂度为 O(1)。

解答

class Solution(object):
def missingNumber(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    N = len(nums)
    total = sum(nums)
    tmp = N*(N+1)/2
    return tmp-total                
    
                   

运行结果

Runtime: 112 ms, faster than 87.25% of Python online submissions for Missing Number.
Memory Usage: 12.8 MB, less than 30.79% of Python online submissions for Missing Number.

每日格言:过去属于死神,未来属于你自己。

请作者买可口可乐 支付宝

支付宝

微信

微信