问题描述:
提示:建议了解Hashmap还有Collections的使用
读取不定个数的整数,然后统计出现频率最高的数
难点分析:
提示:Hashmap十分类似Python中的字典,也是键值对的方式
如果学过python对键值对这样的存储方式一定不陌生
依据题意首先我们需要创建线性表来接受不定个数的整数:
ArrayList<Integer> arrayList = new ArrayList<>();
之后是Hashmap的创建,其实这里还有另一种思路,就是创建treemap,Treemap默认是按值排好序的,所以首先用Treemap的key记录所给数字,用value记录所给值,然后来一步键值对调换就好了,这里我用的Hashmap,主要是直接顺手就用Hashmap做完了,之后才想到Treemap。
Map<Integer, Integer> hasmap = new HashMap<>();
用Hashmap就需要想如何对其值(频率)排序输出,这里我们用Collections工具求得最大频率,让后将Hashmap中得键变成迭代器,放入循环依次查找就好(这里也可以自己写查找算法,一个个的找还是有些慢了):
Integer max = Collections.max(hasmap.values());
Iterator keyIter = hasmap.keySet().iterator();
while (keyIter.hasNext()) {
Integer key001 = (Integer) keyIter.next();
Integer val = (Integer) hasmap.get(key001);
if (val.equals(max)) {
System.out.println("出现次数多的数是:" + key001 + "出现次数:" + val);
}
}
代码:
提示:如果有乱码是ideal的中编码问题,改成英文或者调编码就好
import java.util.*;
public class exe21_6 {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
int a = -1;
do {
a = input.nextInt();
arrayList.add(a);
} while (a != 0);
Map<Integer, Integer> hasmap = new HashMap<>();
for (int i = 0; i < arrayList.size(); i++) {
hasmap.put(arrayList.get(i), hasmap.getOrDefault(new Integer(arrayList.get(i).intValue()), 0) + 1);
}
Integer max = Collections.max(hasmap.values());
Iterator keyIter = hasmap.keySet().iterator();
while (keyIter.hasNext()) {
Integer key001 = (Integer) keyIter.next();
Integer val = (Integer) hasmap.get(key001);
if (val.equals(max)) {
System.out.println("出现次数多的数是:" + key001 + "出现次数:" + val);
}
}
}
}