leetcode 268 Missing Number

原题是:

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 1. Problem Description Given an array containing n distin...
    kakasyw阅读 822评论 0 3
  • Given an array containing n distinct numbers taken from 0...
    Eazow阅读 500评论 0 0
  • 第三章 (梧桐视角) 本文在晋江亦有连载嗷~ 事实上我现在还觉得自己这种头脑一热就去见素未谋面,啊不对是素未谋...
    白龙生阅读 469评论 0 2
  • 支兄刚打开社交蓝图大梦,用户便遭遇史无前例的互坑互骗之局,套路玩转各大社交平台坑蒙拐骗偷盗抢吃喝嫖赌抽,反正大家都...
    杰杰6889阅读 303评论 0 0