How to Find All Duplicates in an Array using Python?

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

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

推荐阅读:
不适当多吃蔬菜也可能造成胃肠不适  帮助预防“三高”心血管疾病的食谱  白酒市场虚假宣传潜规则:年份造假工艺虚标  三种适合春分时节吃的常见养生食物  电脑族需要多吃一些明目功能的食物  有些食物发芽后营养价值会变得更高  春季健康食谱:可以适当吃些新鲜蚕豆  多个品牌婴幼儿配方乳粉被曝配方都一样  新食品安全法“史上最严”建立惩罚制度  适合在夏天吃的既简单又美味的凉拌菜 
评论列表
添加评论