leetcode 268. Missing Number 缺失數字 python 多種思路,一行程式碼
阿新 • • 發佈:2019-02-15
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Approach #1 遍歷速度太慢
# return [i for i in range(len(nums)+1) if i not in nums][0]
# Approach #2 集合操作
# return list(set(list(range(len(nums)+1))) - set(nums))[0]
# Approach #3 從數學角度考慮
# return int(len(nums)*(len(nums)+1)/2 - sum(nums))
# Approach #4 從數學角度考慮
return sum(range(len(nums)+1)) - sum(nums)