我需要打印出数组中最频繁出现的元素的数字。假设我有一个int
数组,如下所示:
int[] array = {1, 2, 3, 3, 3, 5}
然后我将需要打印3,因为这是最常见的元素。但是,我还需要打印出经常出现的元素。可以说我现在有这个数组:
int[] array = {1, 2, 3, 3, 3, 5, 5, 5, 6, 7, 7, 7}
然后我需要打印(排序)3、5和7,因为所有这三个元素都是最常见的元素。所以输出需要看起来像这样:
3
5
7
这是我到目前为止所拥有的代码(仅适用于从最频繁的数字中打印出一个)
Arrays.sort(diceSumArray);
int maxCount = 1;
int index = 1;
int r = diceSumArray[0];
for (int i = 1; i < diceSumArray.length; i++) {
if (diceSumArray[i] == diceSumArray[i-1]) {
index++;
} else {
if (index > maxCount) {
maxCount = index;
r = diceSumArray[i-1];
}
index = 1;
}
}
// not sure where to put the print or if the code below is necessary
System.out.println(r);
if (index > maxCount) {
maxCount = index;
r = diceSumArray[diceSumArray.length -1];
}
HashMap
来实现linear
时间复杂度,在该方法中,您将遍历数组,保存每个项目的出现次数,并返回出现次数最多的项目的列表:private static List<Integer> getMostFreq(int[] arr){
List<Integer> list = new ArrayList<>();
if(arr == null || arr.length == 0)
return list;
HashMap<Integer, Integer> map = new HashMap<>();
for(int num : arr)
if(!map.containsKey(num))
map.put(num,1);
else
map.replace(num, map.get(num)+1);
int max = Integer.MIN_VALUE;
for(HashMap.Entry<Integer,Integer> item : map.entrySet())
if(item.getValue() > max)
max = item.getValue();
for(HashMap.Entry<Integer,Integer> item : map.entrySet())
if(item.getValue() == max)
list.add(item.getKey());
return list;
}