How to Find All Duplicates in an Array using Python?
- 时间:2020-09-07 12:26:38
- 分类:网络文摘
- 阅读:168 次
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) —
推荐阅读:冬季食补:最佳的羊肉吃法,你知道吗 鸡汤虽营养丰富,但这几种病人不要喝 饮食健康与胃病食疗(一):胃病患者饮食注意事项 饮食健康与胃病食疗(二):慢性胃炎的饮食调理 饮食健康与胃病食疗(三):这样饮食降低胃癌风险 冬至时节,常吃这几种传统美食可补阳、防寒! 只有这样吃大蒜才能杀菌防癌,以前你吃对了吗 丝瓜营养丰富,其对人体的保健功效如此之多 患有胃病的人常吃这些食物,可以帮助调理好胃 山药营养丰富食疗价值高,助爱美女性吃出好身材
- 评论列表
-
- 添加评论