Map<Integer, Integer> map = new HashMap<>();
for (int n : arr) map.put(n, map.getOrDefault(n, 0) + 1);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> map.get(a) - map.get(b));
for (int n : arr) pq.add(n);
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
假设输入arr为[4,3,1,1,3,3,2,2] 然后我们将它们全部放入 pq 并一一轮询它们。 正确的顺序应该是按频率顺序排列为 4 1 1 2 2 3 3 3。
但是输出顺序是 4 1 2 2 1 3 3 3,没有输出正确的顺序。
最佳答案
顺序正确。 PriorityQueue
不保证关系如何被打破,并且 1 和 2 是并列的:
If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily.
如果您想选择平局的订单,那么您的比较器应该这样做。最简单的方法是编写 Comparators.comparingInt(i -> map.get(i)).thenComparingInt(i -> i)
以升序打破平局。
关于java优先级队列没有根据hashmap的频率获得正确的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65801575/