如何获得重复次数最少的数字?
例如:
答案 0 :(得分:3)
你可以这样做:
a = [1,1,1,2,3,3,4,4,5,6,6,2,3,4]
a.group_by{|i| a.count(i) }
#=> {1=>[5], 2=>[2, 2, 6, 6], 3=>[1, 1, 1, 3, 3, 3, 4, 4, 4]}
然后从那个Hash中选择你想要的东西(哈希的关键是项目数)
答案 1 :(得分:3)
这应该有效:
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
答案 2 :(得分:1)
>> h = [1,1,1,2,3,3,4,4,5,6,6,2,3,4].inject(Hash.new(0)) { |x,y| x[y]+=1;x }.select{|x,y| y>1 }
=> {1=>3, 2=>2, 3=>3, 4=>3, 6=>2}
>> h.values.min
=> 2
>> h.each{|x,y| puts "#{x} #{y}" if y==h.values.min }
2 2
6 2
=> {1=>3, 2=>2, 3=>3, 4=>3, 6=>2}
>>