原題是:
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?
思路是:
求和以政,不缺數(shù)字時(shí)的和,減去缺一個(gè)數(shù)字的和肌似,得到所缺的那個(gè)數(shù)字热凹。
代碼是:
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內(nèi)置的sum函數(shù)。