我怎样才能有效地提取在Ruby数组重复的元素? [英] How can I efficiently extract repeated elements in a Ruby array?

查看:1046
本文介绍了我怎样才能有效地提取在Ruby数组重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像[1,1,1,2,4,6,3,3]数组,我想获得重复的元素的列表,在这种情况下[1,3]。我写这样的:

I have an array like [1,1,1,2,4,6,3,3] and I would like to get the list of repeated elements, in this case [1,3]. I wrote this:

my_array.select{|obj|my_array.count(obj)>1}.uniq

但它是可悲的低效(O(N²))。你有一个更好的主意吗?如果可能的话简洁。

But it is tragically inefficient (o(n²)). Do you have a better idea? If possible concise.

感谢

推荐答案

伊利亚Haykinson的回答启发:

Inspired by Ilya Haykinson's answer:

def repeated(array)
  counts = Hash.new(0)
  array.each{|val|counts[val]+=1}
  counts.reject{|val,count|count==1}.keys
end

这篇关于我怎样才能有效地提取在Ruby数组重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆