更新时间:2023-11-28 16:24:46
首先构建一个哈希,将数组中的每个值映射到它的频率……
First build a hash mapping each value in the array to its frequency…
arr = [1, 1, 1, 2, 3]
freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}
…然后用频率表找出频率最高的元素:
… then use the frequency table to find the element with the highest frequency:
arr.max_by { |v| freq[v] }
#=> 1