1. 程式人生 > >leetcode 268. Missing Number 缺失數字 python 多種思路,一行程式碼

leetcode 268. Missing Number 缺失數字 python 多種思路,一行程式碼

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)