題目:
找到所有數組中消失的數字:給定一個范圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。
給定一個范圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。
找到所有在 [1, n] 范圍之間沒有出現在數組中的數字。
您能在不使用額外空間且時間復雜度為O(n)的情況下完成這個任務嗎? 你可以假定返回的數組不算在額外空間內。
示例:
輸入:
[4,3,2,7,8,2,3,1]
輸出:
[5,6]
思路:
哈希表。
程序:
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: if not nums: return [] result = [] myHashMap = set() for num in nums: myHashMap.add(num) for index in range(1, len(nums) + 1): if index not in myHashMap: result.append(index) return result