Leetcode 442. Find All Duplicates in an Array

Question

Solution1

考虑使用字典,如果当前元素已经在字典中,添加到output中。

1
2
3
4
5
6
7
8
9
10
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
dicct = {}
output = []
for i in range(len(nums)):
if nums[i] not in dicct:
dicct[nums[i]] = 1
else:
output.append(nums[i])
return output

Solution2

如果不适用额外空间,考虑在原序列上进行修改。因为a[i] < n, 考虑对每个元素除以n,然后求余数,对余数-1,这样操作以后,就找到了对应元素如果排序后所在的index,在对应index元素的位置加上n。如果该元素出现两次,则加了两个n。如果最后这个位置的数大于了2n,贼该位置的index出现了两次。

1
2
3
4
5
6
7
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
for num in nums:
i = num % n -1
nums[i] += n
return [i+1 for i in range(len(nums)) if nums[i] > 2*n]