有一个整数数组:
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( 时间内存储待排序数组的出现次数,假设您不必调整数组的大小。 如果你可以使用库,我建议使用哈希图。
排序:希望这不会像"自己查找"类型的答案,但看看您是否可以搜索排序算法。 有一堆,从气泡排序(易于编码但速度慢(到快速排序(更难编码但更快(。 应该有很多用于在线简单排序算法的 java 教程,这些教程正是您正在寻找的内容。