为什么无法从优先队列中通过 peek() 获取的元素中移除它?

huangapple go评论72阅读模式
英文:

Why can't I remove an element gotten by peek() from the PriorityQueue?

问题

以下是翻译好的代码部分:

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());   

它就正常工作了。为什么会这样呢?

英文:

Here is my code.

class MinStack {
    public Deque&lt;Integer&gt; deque = new LinkedList&lt;Integer&gt;();
    public PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;Integer&gt;();

    public MinStack() {
        Deque&lt;Integer&gt; deque = new LinkedList&lt;Integer&gt;();
        PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;Integer&gt;();
    }
    
    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();
    }
}

In the function pop(), the PriorityQueue doesn't delete the top value I get from the deque.peek().
When I changed it to

pq.remove(deque.pollLast());   

It worked. Why is that?

答案1

得分: 2

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

英文:

Deque.peek() returns the first element of the deque, same as peekFirst(). Use peekLast() instead like you did in top().

huangapple
  • 本文由 发表于 2020年4月11日 02:03:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/61146048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定