https://leetcode.com/problems/find-all-duplicates-in-an-array/
Solution
set is an collection of elements without duplicates, we use this property to solve the problem:
Execute an iteration cross the given array, meanwhile:
- check the length of current set
- add current element from the array into the set
- go back to 1., if there is no change in the length, then it indicates that the added element is duplicated
Submissions
- faster than 87.10%
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
myset=set()
result=[]
for i in nums:
length=len(myset)
myset.add(i)
if length==len(myset):
result+=[i]
return result
Top comments (0)