我必须用Java编写代码来查找数组中所有最大的整数。目前,我的代码只返回一种模式,尽管有多个整数具有相同的模式值。任何建议将不胜感激。 提前致谢
public static int getMode(int[] values) {
if(values.length==0)
return null;
HashMap<Integer,Integer> freqs = new HashMap<Integer,Integer>();
for (int val : values) {
Integer freq = freqs.get(val);
freqs.put(val, (freq == null ? 1 : freq+1));
}
int mode = 0;
int maxFreq = 0;
for (Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
int freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return mode;
}
答案 0 :(得分:0)
// ...
// first, you find out what the maximum frequency is
int maxFreq = 0;
for (Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
int freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
}
}
// then, you collect all keys that share the same frequency
List<Integer> modes = new LinkedList<Integer>();
for (Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
int freq = entry.getValue();
if (freq == maxFreq) {
modes.add(entry.getKey());
}
}
return modes;