如何得到重复次数最少的数字?
例如:
- 从 [1,2,3,4,5,6,6,2,3,4,6] 返回 [1] 因为“1”只重复一次,而其他重复 2 次或更多次。<
- 从 [1,1,1,2,3,3,4,4,5,6,6,2,3,4] 返回 [2,6] 因为“2”和“6”都只是对于其他数字重复两次而不是三次或更多次。
最佳答案
这应该有效:
a.group_by{|e| a.count(e)}.min[1].uniq
ruby-1.9.2-p136 :040 > a = [1,1,1,2,3,3,4,4,6,6,2,3,4]
ruby-1.9.2-p136 :041 > a.group_by{|e| a.count(e)}.min[1].uniq
=> [2, 6]
ruby-1.9.2-p136 :044 > a = [1,2,3,4,6,6,2,3,4,6]
ruby-1.9.2-p136 :045 > a.group_by{|e| a.count(e)}.min[1].uniq
=> [1]
更新:O(n) 次
def least_frequent(a)
counts = Hash.new(0)
a.each{|e| counts[e] += 1}
least =[nil, []]
counts.each do |k,v|
if least[0].nil?
least[0] = v
least[1] = k
elsif v < least[0]
least[0] = v
least[1] = [k]
elsif v == least[0]
least[1] << k
end
end
least[1]
end
以下是第一种和第二种方法之间的基准测试(运行此测试 10,000 次):
user system total real
first 10.950000 0.020000 10.970000 ( 10.973345)
better 0.510000 0.000000 0.510000 ( 0.511417)
数组设置为:
a = [1,1,1,2,3,3,4,4,6,6,2,3,4] * 10
关于ruby - 如何获取数组中重复次数最少的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5508652/