2018-11-06
2018-11-06 本文已影响0人
pythonpy
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.
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?
分析:题目要求在线性时间复杂度,常量级额外空间完成,这就意味着无法通过排序解题,应用暴力求解,分别判断每个数字是否确实,时间超时,笔者想了一个很低端的办法,就是把给定的数组进行加和,然后利用(首项+末项)*项数/2计算给定的n的总和,将总和减去给定的每一项,最后剩下的数字即为所求
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#计算给定n值得总和
sums = (1+len(nums))*len(nums)//2
for i in nums:
sums -= i
return sums