如何在数组中查找出现次数最多的项目 [英] How to find an item in array which has the most occurrences

查看:114
本文介绍了如何在数组中查找出现次数最多的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在数组中找到出现次数最多的项目?

How do I find an item in array which has the most occurrences?

[1, 1, 1, 2, 3].mode
=> 1

['cat', 'dog', 'snake', 'dog'].mode
=> dog

推荐答案

首先构建一个哈希,将数组中的每个值映射到其频率…

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

这篇关于如何在数组中查找出现次数最多的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆