How to Find All Duplicates in an Array using Python?

  • 时间:2020-09-07 12:26:38
  • 分类:网络文摘
  • 阅读:119 次

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) —

推荐阅读:
百度正式上线快速收录功能  如何让百度快速收录网页?快用百度站长平台“快速收录”功能!  php和asp网站源码有什么不同?哪种代码语言更好?  装修公司网销业绩不好?原因和解决方法都在这里  亚马逊正式推出企业搜索引擎Kendra  为什么Google SEO见效慢  一个三流SEOer从业记录  网站权重如何提升,掌握以下几点快速提权  SEO关键词排名该掌握的核心优化技巧  为何网站内容稳定更新还没有关键词排名? 
评论列表
添加评论