这是我的代码。
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());
它成功了。这是为什么?
最佳答案
Deque.peek()
返回双端队列的第一个元素,与 peekFirst()
相同。使用 peekLast()
代替,就像在 top()
中所做的那样。
关于java - 为什么我无法从 PriorityQueue 中删除通过 peek() 获取的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61146048/