LeetCode 442. [Python] Find All Duplicates in an Array
原题链接
中等
作者:
徐辰潇
,
2020-02-25 03:13:34
,
所有人可见
,
阅读 657
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
#The straightforward stragtegy is to create a Set to store what appears before.
#However, ti takes O(n) space
#The trick used here is to the nums itself as a Set
#Time complexity: O(n)
#Space complexity: O(1)
res = []
for ele in nums:
idx = abs(ele) - 1
if nums[idx] < 0:
res.append(abs(ele))
else:
nums[idx] *= -1
return res