假设我有一个 double 组,如下所示:
Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}
我需要一个函数来确定数组中的 MAJORTY 投票是什么,在本例中为“10”,因为它是出现次数最多的数字... 当然也有不存在多数的情况(他们是平等的),在这种情况下我需要抛出一个异常...
有什么线索吗?除了在数组上做一些非常讨厌的循环(对于每个索引,确定有多少个具有相同的值,在数组中存储一个计数,然后扫描计数数组以获得最高的数字,该位置的值是赢家等等……)
最佳答案
使用 Map<Integer, Integer>
应该很简单:
int mostFrequent(int... ary) {
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int a : ary) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
int max = -1;
int mostFrequent = -1;
for (Map.Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
return mostFrequent;
}
关于java - 确定数组中最常见的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852631/