【问题标题】:Why can't I remove an element gotten by peek() from the PriorityQueue?为什么我不能从 PriorityQueue 中删除 peek() 获取的元素?
【发布时间】:2020-07-23 13:00:53
【问题描述】:

这是我的代码。

class MinStack {
    public Deque<Integer> deque = new LinkedList<Integer>();
    public PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

    public MinStack() {
        Deque<Integer> deque = new LinkedList<Integer>();
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    }

    public void push(int x) {
        deque.offer(x);
        pq.offer(x);
    }

    public void pop() {
        pq.remove(deque.peek()); 
        deque.pollLast();        
    }

    public int top() {
        return deque.peekLast();
    }

    public int getMin() {
        return pq.peek();
    }
}

在函数 pop() 中,PriorityQueue 不会删除我从 deque.peek() 获得的最高值。 当我将其更改为

pq.remove(deque.pollLast());   

成功了。这是为什么呢?

【问题讨论】:

    标签: java deque peek


    【解决方案1】:

    Deque.peek() 返回双端队列的第一个元素,与peekFirst() 相同。像在 top() 中那样使用 peekLast()

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      相关资源
      最近更新 更多