从哈希图中获取具有最大值的键?
我有一个像这样定义的 HashMap
...
HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();
它存储一个名称以及该名称的出现情况。例如...
uniqueNames.put("lastname",42);
我怎样才能得到出现次数最多的名字?
有关更多信息,我正在使用“人”的二叉搜索树,将唯一的名称和频率存储在 HashMap
中。我想做的是打印最常见的姓氏,有人告诉我使用 HashMap
因为我想将 String
与 Integer< 一起存储/代码>。也许我应该使用一个类来存储名称和频率?有人可以提供一些建议吗?
I have a HashMap
defined like this...
HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();
It stores a name, and the occurence of that name. For example...
uniqueNames.put("lastname",42);
How can I get the name with the highest occurrence?
For some more information, I'm working with a binary search tree of "people", storing the unique names and frequencies in a HashMap
. What I want to do is to print the most common last names, and someone told me to use HashMap
as I wanted to store a String
together with an Integer
. Maybe I should use a class to store the name and frequency instead? Could someone please offer some suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果必须使用 HashMap,那么最简单的方法可能就是循环遍历 Map 寻找最大值
If you have to use a HashMap, then the simplest way is probabably just to loop through the Map looking for the maximum
最明显的是,现在允许具有最大出现值的多个:
另一个选择是使用 Guava 的 BiMap。
Most obvious, now allowing for multiple with largest occurrence value:
Another option would be to use Guava's BiMap.
实际上有两种方法可以解决这个问题。
如果您要经常这样做,我实际上建议反向存储映射,其中键是名称出现的次数,值是出现多次的名称列表。我还会使用 HashMap 在另一个方向上执行查找。
与删除类似的东西...
最后,对于您的搜索:
返回出现次数最多的名称列表。
如果这样做,搜索可以在 O(log n) 内完成,但空间需求会增加(尽管仅增加一个常数因子)。
如果空间是问题,或者性能不是问题,只需迭代 uniqueNames.keySet 并跟踪最大值。
There are two ways of going about this actually.
If you are going to be doing this frequently, I would actually suggest storing the mapping in reverse, where the key is the number of times a name has appeared, and the value is a list of names which appeared that many times. I would also use a HashMap to perform the lookups in the other direction as well.
Something similar for deleting...
And finally, for your search:
Returns the List of names that have the max occurrences.
If you do it this way, the searching can be done in O(log n) but the space requirements increase (only by a constant factor though).
If space is an issue, or performance isn't a problem, simply iterate through the uniqueNames.keySet and keep track of the max.
似乎您想要一些类似于
SortedMap
的东西,但它是根据值而不是键排序的。我认为标准 API 中不存在这样的东西。最好创建一个Frequency 类并将实例存储在
SortedSet
中。输出:
Seems like you want something a bit like a
SortedMap
but one sorted on the value, not the key. I don't think such a thing exists in the standard API.It might be better to create a Frequency class and store instances in a
SortedSet
instead.Output:
这是我的方法。
This is my approach.
1.试试这个可能会有帮助。
1.Try this it may help.
如果你只想要价值,你可以选择这个。在这个例子中我必须得到
“n”个数字数组中某个数字的最大频率
If you only want the value you can go for this. In this example I had to get the
maximum frequency of a number among an array of 'n' numbers