ruby - 如何获取数组中重复次数最少的数字?

标签 ruby algorithm

如何得到重复次数最少的数字?

例如:

  • 从 [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/

相关文章:

ruby-on-rails - 在测试中模拟嵌套参数

objective-c - 具有多个客户端的 Ruby UDP 服务器?

c - 生成对的所有排列,不包括单个元素的排列

c - 简单计算器不适用于 C 中的大数字

Ruby Mechanize 登录不工作

ruby-on-rails - Rails - 父类(super class)不匹配

python - 整数数学推导(运算顺序)

java - 对冒泡排序程序进行 2 次修改

html - 预编译后 html 图像路径是否仍然有效?

java - 最小位程序