英文:
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<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();
    }
}
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().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论