How to Find All Duplicates in an Array using Python?
- 时间:2020-09-07 12:26:38
- 分类:网络文摘
- 阅读:177 次
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) —
推荐阅读:哪些健脑食品有助于增强孩子的记忆力 食药监总局:明确乳粉企业监督检查规定 什么叫转基因食品 如何判断转基因食品 教你辨别常见的几种带有转基因的食品 冬季食疗进补过度容易导致咽喉干痛 大雪节气吃什么食物可以缓解皮肤干燥 乳品企业涨价之余更应重视质量和安全 食用调和油将被要求标识各植物油比例 胶原蛋白的美丽谎言 暴利驱动的疯狂营销 常见的六大清肠食物可降低血胆固醇
- 评论列表
-
- 添加评论