如何有效地提取 Ruby 数组中的重复元素? [英] How can I efficiently extract repeated elements in a Ruby array?

查看:14
本文介绍了如何有效地提取 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.

谢谢

推荐答案

灵感来自 Ilya 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天全站免登陆