微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用排序数组查找优先级队列的最小/最大元素

如何解决使用排序数组查找优先级队列的最小/最大元素

如果我想实现一个可以让我有效地识别 PriorityQueue 的最小值/最大值的数据结构,如果我使用循环排列的数组表示来实现 PriorityQueue,它会起作用吗? min 和 max 元素位于数组的两端?为什么或者为什么不?提前致谢!

解决方法

您可以在 addofferpoll 方法中扩展 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。