How to Find All Duplicates in an Array using Python?
- Time:2020-09-07 12:26:38
- Class:Weblog
- Read:143
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]Output:
[2,3]
Using Python’s Collections.Counter to Find All Duplicates in Array
Using collections.Counter in Python allows us to count the frequencies of the elements in an array or list in Python. Then, we can use the List comprehensions to create a list of the duplicate elements in an array by checking their frequencies. Finally, we need to convert it to set, this allows us to filter out the duplicates in the duplicates.
1 2 3 4 | class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: c = collections.Counter(nums) return set([x for x in nums if c[x] > 1]) |
class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: c = collections.Counter(nums) return set([x for x in nums if c[x] > 1])
This solution requires O(N) time and O(N) space as we are storing the frequencies in a dictionary object.
–EOF (The Ultimate Computing & Technology Blog) —
Recommend:Summits set epoch-making milestone in history of China-Arab ties
In the face of COVID-19 pandemic, China and Arab countries have
15 Macao residents qualify as candidates for deputies to nationa
Study finds genetic solution to pre-harvest sprouting in rice, w
Bodybuilders dying as coaches, judges encourage extreme measures
Malta's Marsaskala, China's Dujiangyan sign sister city agreemen
U.S. mortgage applications continue slide amid surging interest
Russian, UAE presidents discuss bilateral cooperation over phone
Hate crimes in U.S. Los Angeles County rise to highest level sin
Chinese mainland reports 4,031 new local confirmed COVID-19 case
- Comment list
-
- Comment add