简体   繁体   English

如何查看 java.util.PriorityQueue 的尾部?

[英]How can I peek the tail of a java.util.PriorityQueue?

So I am playing with the source code of the java.util.PriorityQueue .所以我在玩java.util.PriorityQueue的源代码。 You can check it here: http://kickjava.com/src/java/util/PriorityQueue.java.htm你可以在这里查看: http : //kickjava.com/src/java/util/PriorityQueue.java.htm

I am in need to peek the tail of the queue.我需要查看队列的尾部。 This class only offers peeking the head of the queue.这个类只提供窥视队列的头部。 Is there an easy way that I can modify this class to allow me to pick the tail?有没有一种简单的方法可以修改这个类以允许我选择尾部?

I am looking for any change / smart hack in this class to allow me to do that.我正在寻找本课程中的任何更改/智能技巧以允许我这样做。 My first try was to peek queue[size] but it did not work.我的第一次尝试是查看queue[size]但它没有用。

Java's PriorityQueue, like most priority queues, is implemented with a heap. Java 的 PriorityQueue 和大多数优先级队列一样,是用堆实现的。

A heap is a data structure that maintains only the property that all parents are less than their children, or all parents are greater than their children.堆是一种数据结构,它只维护所有父母都小于他们的孩子,或者所有父母都大于他们的孩子的属性。 There is no inherent ordering among children.孩子之间没有固有的秩序。

Thus, the only way to find the tail would be to do a linear search among the bottom layer, which costs O(n) time for a size n priority queue.因此,找到尾部的唯一方法是在底层之间进行线性搜索,对于大小为n优先级队列,这花费O(n)时间。

Yes, but the at the cost of extra space complexity:是的,但以额外的空间复杂性为代价:

PriorityQueue<Integer> pqNew = new PriorityQueue<>(java.util.Collections.reverseOrder());

Now add the elements of your PriorityQueue into this pqNew .现在将PriorityQueue的元素添加到这个pqNew Therefore, pqNew.peek() will give you the required answer ie the tail element of your original PriorityQueue .因此, pqNew.peek()将为您提供所需的答案,即原始PriorityQueue的尾部元素。

How about use toArray() method and access the last position?如何使用 toArray() 方法并访问最后一个位置?

PriorityQueue<Integer> pq = new PriorityQueue<>(3);
pq.offer(1); pq.offer(2); pq.offer(3);
System.out.println((int) pq.toArray()[pq.size()-1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM