更新于2019.6.17 22:56
题目描述
题目含义是,假设有一个长度为n+1的数组
(其取值为[0,1,2,...,n])
,随机拿掉一个数,使之变为长为n的array,打乱顺序问拿掉的数是几?
t i m e : O ( n l o g n ) ; s p a c e : O ( 1 ) time:O(nlogn);space:O(1) time:O(nlogn);space:O(1)
想法是如果先排序,那么遍历的时候会很容易判断前后两个数是否差值为1。这个好像能补上上次缺的方法。
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
if nums[-1]!=len(nums): #ensure not loss final num
return len(nums)
if nums[0] != 0: #ensure not loss first num
return 0
for i in range(1,len(nums)):
if nums[i-1]+1 != nums[i]: #if integer not obey this func, means something wrong.
# print(nums[i-1]+1)
return nums[i-1]+1
S = Solution()
# nums = [3,0,1]
nums = [9,6,4,2,3,5,7,0,1]
S.missingNumber(nums)
Runtime: 136 ms, faster than 28.83% of Python online submissions for Missing Number.
Memory Usage: 12.7 MB, less than 79.39% of Python online submissions for Missing Number.
t i m e : O ( n ) ; s p a c e : O ( n ) time:O(n);space:O(n) time:O(n);space:O(n)
nums = set(nums) #python中set的空间开销为$O(n)$
for i in range(len(nums)+1):
if i not in nums:
# print(i)
return i
Runtime: 116 ms, faster than 72.13% of Python online submissions for Missing Number.
Memory Usage: 13.3 MB, less than 6.49% of Python online submissions for Missing Number.
t i m e : O ( n ) ; s p a c e : O ( 1 ) time:O(n);space:O(1) time:O(n);space:O(1)
这个方法就比较机灵了,利用高斯累加和减去所有值之和即可得到最终值
tmp = 0
L = len(nums)
summation = L*(L+1)//2
print(summation)
for i in range(L):
tmp = tmp + nums[i]
# print(tmp)
# print(summation-tmp)
return summation-tmp
Runtime: 108 ms, faster than 85.34% of Python online submissions for Missing Number.
Memory Usage: 12.9 MB, less than 29.26% of Python online submissions for Missing Number.
t i m e : O ( ) ; s p a c e : O ( ) time:O();space:O() time:O();space:O()
最后一种之前没接触过,其实就是位运算,拿数组下标与对应的值做或运算
,根据相同为0,不同为1
的运算规则,得到1时即可判断缺失值。我好像想的太简单了,一下子卡住了...
参考:Leetcode268