Python實現"缺失數字"的四種方法
阿新 • • 發佈:2018-12-12
給定一個包含 0, 1, 2, ..., n
中 n 個數的序列,找出 0 .. n 中沒有出現在序列中的那個數
Example 1:
Input: [3,0,1] Output: 2Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8
注意:
必須線上性時間複雜度內完成,嘗試用常數階額外空間完成
1:申請len(nums)+1長度的陣列用於標記,兩次for迴圈完成工作。時間複雜度O(n),空間複雜度O(n)
def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ checkList = [False] * (len(nums) + 1) for i in nums: checkList[i] = True for i, j in enumerate(checkList): if not j: return i
2:0~n,滿足等差數列公式(參考他人)
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (len(nums) * (len(nums)+1) // 2) - sum(nums)
3:^位運算(參考他人)
def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ bit = 0 for i, j in enumerate(nums): bit ^= i ^ j return bit ^ len(nums)
4:set()方法(參考他人)
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (set(range(len(nums) + 1)) - set(nums)).pop()