DEV Community

Effy L.H.
Effy L.H.

Posted on

LeetCode:442. Find All Duplicates in an Array

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:

  1. check the length of current set
  2. add current element from the array into the set
  3. 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)