问题描述
如果我想实现一个可以让我有效地识别 PriorityQueue
的最小值/最大值的数据结构,如果我使用循环排列的数组表示来实现 PriorityQueue
,它会起作用吗? min 和 max 元素位于数组的两端?为什么或者为什么不?提前致谢!
解决方法
您可以在 add
、offer
和 poll
方法中扩展 PriorityQueue 并更新最大值。
类似于下面的代码。根据您的需要改进/修复代码。
public class Test {
public static void main(String[] args) {
MyPQ<Integer> pq = new MyPQ<>();
pq.offer(3);
pq.offer(44);
pq.offer(1);
pq.offer(10);
System.out.println("Max:" + pq.getMax() + " Min:" + pq.getMin());
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println("Max:" + pq.getMax() + " Min:" + pq.getMin());
}
}
class MyPQ<E extends Comparable<E>> extends PriorityQueue<E>{
private E max;
private void setMax(E e) {
if(max == null)
max = e;
else if(e.compareTo(max) > 0) {
max = e;
}
}
public E getMax() {
return max;
}
public E getMin() {
return super.peek();
}
@Override
public boolean offer(E e) {
setMax(e);
return super.offer(e);
}
@Override
public boolean add(E e) {
setMax(e);
return super.add(e);
}
@Override
public E poll() {
E min = super.poll();
if(min.equals(max))
max=null;
return min;
}
}
输出:
Max:44 Min:1
1
3
10
44
Max:null Min:null