想不出比将整个集合复制到另一个集合并使用 poll 方法更好的方法,用 PQ 自然排序打印 toString。
还有其他建议吗?
最佳答案
如果您需要 PriorityQUeue 完全排序后的顺序,则需要将其复制到 TreeSet 等排序集合
例如
System.out.println(new TreeSet(pq)); // prints elements naturally sorted.
注意:这将丢弃重复项,而 PriorityQueue 不会。
<小时/>尽管排序是 O(n * log n) 并且打印是 O(n) 这并不是故事的全部。在内存中排序比使用任何 IO 快得多,这意味着您需要一个非常大的队列才能使排序更加重要。
public static void main(String... args) {
PriorityQueue<Double> pq = new PriorityQueue<Double>();
for (int i = 0; i < 10*1000 * 1000; i++)
pq.add(Math.random());
long start1 = System.nanoTime();
Set<Double> set = new TreeSet<Double>(pq);
long time1 = System.nanoTime() - start1;
long start2 = System.nanoTime();
for (Double d : set) {
System.out.println(d);
}
long time2 = System.nanoTime() - start2;
System.out.printf("It took %.3f seconds to sort, and %.3f seconds to print %,d doubles%n", time1 / 1e9, time2 / 1e9, pq.size());
}
打印在最后
It took 28.359 seconds to sort, and 94.844 seconds to print 10,000,000 doubles
如果我使用数组并对其进行排序
Double[] doubles = pq.toArray(new Double[pq.size()]);
Arrays.sort(doubles);
It took 8.377 seconds to sort ....
简而言之,在队列足够长以进行最重要的排序之前,您可能会耗尽内存或超过字符串的最大长度。
关于java - 优先队列\java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12404566/