您需要一个地图(又名字典)数据结构来解决这个问题。这是我能想到的最快、最简洁的解决方案。
public static void main(String[] args){
int[] arr = new int[]{10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10};
printMostFrequent(arr);
}
private static void printMostFrequent(int[] arr){
// Key: number in input array
// Value: amount of times that number appears in the input array
Map<Integer, Integer> counts = new HashMap<>();
// The most amount of times the same number appears in the input array. In this example, it's 4.
int highestFrequency = 0;
// Iterate through input array, populating map.
for (int num : arr){
// If number doesn't exist in map already, its frequency is 1. Otherwise, add 1 to its current frequency.
int currFrequency = counts.getOrDefault(num, 0) + 1;
// Update frequency of current number.
counts.put(num, currFrequency);
// If the current number has the highest frequency so far, store its frequency for later use.
highestFrequency = Math.max(currFrequency, highestFrequency);
}
// Iterate through unique numbers in array (remember, a Map in Java allows no duplicate keys).
for (int key : counts.keySet()){
// If the current number has the highest frequency, then print it to console.
if (counts.get(key) == highestFrequency){
System.out.println(key);
}
}
}
输出
6
10