[LeetCode] #442. Find All Duplicates in an Array
題目 Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice , return an array of all the integers that appears twice . You must write an algorithm that runs in O(n) time and uses only constant extra space. 直覺解 構想: 用 seen 把出現過的數字存起來。如果遇到已經在 seen 裡面的數字,那就是重複的(不符合 uses only constant extra space)。 python 3 實作: class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: ans = [] seen = {} for num in nums: if num not in seen: seen[num] = True else: ans.append(num) return ans 效能: Runtime: 351 ms, faster than 76.63% of Python3 online submissions for Find All Duplicates in an Array. Memory Usage: 22.8 MB, less than 19.60% of Python3 online submissions for Find All Duplicates in an Array. 研究別人的解 來源:sample 308 ms submission 構想:List comprehension 和 set(不符合 uses only const...