用HashMap<Integer, Integer>,数组元素做key,出现次数做value;遍历数组,出现一次,value++;
代码:
public class CountNumber{
public static void mian(String[] args){
int[] arr = {1,2,3,4,8,2,2,5,3,1,2,4,5,2}
int[] ans = maxTimsx(arr);
System.out.println("数字:" + ans[0] + "出现" + ans[1] + "次")
}
public static int[] maxTimes(int[] arr){
if(arr == null || arr.length < 1){
return null;
}
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int times = 0;
int number = 0;
for(i=0;i<arr.length;i++){
if(map.get(arr.[i]) == null){
map.put(arr[i],1)
}
}else{
integer value = map.get(arr[i]) + 1;
map.put(arr[i],value)
if(value > times){
times = value;
number = arr[i];
}
}
return new int[] {number,times};
}
}
本文介绍了一种使用HashMap<Integer,Integer>来统计数组中各元素出现次数的方法。通过将数组元素作为key,出现次数作为value,遍历数组并更新HashMap,最终找出出现次数最多的元素及其出现次数。

1093

被折叠的 条评论
为什么被折叠?



