[leetcode: Python]268. Missing Number

来源:互联网 发布:php curl 文件上传 编辑:程序博客网 时间:2024/06/16 20:01

题目:
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?
题意:
给定一个数组包含n个数,这n个数取自0到n的序列,求失踪的那个数。
要求:
时间复杂度O(n),空间复杂度O(1)

方法一:性能88ms
sum1 为0到n的和,sum2为给定数组的和,求两者的差异。考虑到数组排序后,nums[0] != 0的情况。

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

方法二:性能45ms

import mathclass Solution(object):    def missingNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        num_total = sum(nums)        n = len(nums)        total = (n * (n + 1)) / 2        return total - num_total
0 0
原创粉丝点击