有一个int数组:
int[] arr = new int[] {8, 9, 7, 6, 7, 8, 8, 9};
如何计算每个数字的出现次数,然后对其进行排序,以便数字的打印及其出现以升序显示?像这样:
6(1) 7(2) 8(3) 9(2)
不使用任何库,只是循环和ifs,最有效的方法是什么?
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.这将存储要进行排序的事件在O(n)时间内的数组,假设您不必调整数组大小。如果你可以使用库我会建议使用hashmap。
排序:希望这不是“自己查找”类型的答案,但看看你是否可以搜索排序算法。其中有很多,从冒泡排序(易于编码但速度慢)到快速排序(更难编码但更快)。应该有大量的java教程,用于简单的在线排序算法,这些算法正是您所需要的。