这是我的代码。
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()
。