有一个int数组:
int[] arr = new int[] {8, 9, 7, 6, 7, 8, 8, 9};
如何计算每个数字的出现次数,然后对其进行排序,以便按升序显示数字及其出现次数?像这样:
6(1) 7(2) 8(3) 9(2)
不使用任何库,只是循环和ifs,什么是最有效的方法?
答案 0 :(得分:0)
int[] arr = new int[] {8, 9, 7, 6, 7, 8, 8, 9};
Map<Integer, Integer> map = new TreeMap<>(); // TreeMap sorts keys in their natural order
for(int i : arr) {
if(!map.containsKey(i)) { // if map doesn't contain currently checked int as a key...
map.put(i, 1); // put it to map with corresponding value equal to one
} else { // it this int is already in map...
map.put(i, map.get(i) + 1); // put it into map with incremented value
}
}
System.out.println(map.entrySet());
你得到的输出:
[6=1, 7=2, 8=3, 9=2]
答案 1 :(得分:0)
查找事件:尝试创建第二个数组,在此数组中使用待排序数组中的数字作为此新数组的索引,并将该索引处的值更新为1.这将假设您不必调整阵列大小,请在O(n)时间内存储待排序数组的出现次数。如果您可以使用库,我建议使用散列图。
排序:希望这不是“自己查找”类型的答案,但看看你是否可以搜索排序算法。其中有很多,从冒泡排序(易于编码但速度慢)到快速排序(更难编码但更快)。应该有大量的在线简单排序算法的java教程,这些算法正是你想要的。