剑指offer 59 - II. 队列的最大值
题目描述
解题思路
单调队列
注意,此题有两个注意点!!
- 只要涉及栈和队列,一定要注意边界判空问题。例如,只要涉及
getLast
、getFirst
这种取元素,或者poll
这种移除元素,就一定要判空。 - 只要不是基本数据类型,其他所有的包装器类型比较值大小时,一定要用 equals 。如
Integer
class MaxQueue {
Queue<Integer> myQue;
LinkedList<Integer> maxQue;
public MaxQueue() {
myQue = new LinkedList<>();
maxQue = new LinkedList<>(); //单调队列,从队头到队尾保持递减
}
public int max_value() {
return maxQue.isEmpty() ? -1 : maxQue.getFirst();
}
public void push_back(int value) {
myQue.offer(value);
//注意!由于需要取队头元素,所以一定要判空
while (!maxQue.isEmpty() && value > maxQue.getLast()) {
maxQue.removeLast(); //将两个高个儿之间的元素全部出队
}
maxQue.addLast(value);
}
public int pop_front() {
if (myQue.isEmpty()) return -1;
//注意!有大坑!由于是包装器类型Integer,所以一定要用equals比较
if (myQue.peek().equals(maxQue.getFirst())) maxQue.removeFirst();
return myQue.poll();
}
}
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/