建立一个HashMap,键存储数据,值存储出现的次数;
找出值最大的那个,返回所对应的键。
public static int findMax(int[] a) {
if (a.length == 0) {
return Integer.MAX_VALUE;
}
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int num : a) {
if (!hashMap.containsKey(num)) {
hashMap.put(num, 1);
} else {
hashMap.put(num, hashMap.get(num) + 1);
}
}
Set<Integer> keySet = hashMap.keySet();
int maxTimes = Integer.MIN_VALUE;
int maxValue = 0;
for (int key : keySet) {
if (hashMap.get(key) > maxTimes) {
maxTimes = hashMap.get(key);
maxValue = key;
}
}
return maxValue;
}