剑指 Offer 59 - II. 队列的最大值
思路:单调双向队列
维护单调队列保存队列所有递减的元素
class MaxQueue {
public:
MaxQueue() {
}
int max_value() {
if(curQueue.empty())
return -1;
return maxQueue.front();
}
void push_back(int value) {
curQueue.push_back(value);
while(maxQueue.size()&&maxQueue.back()<value) maxQueue.pop_back();
maxQueue.push_back(value);
}
int pop_front() {
if(curQueue.empty())
return -1;
int value=curQueue.front();
curQueue.pop_front();
if(maxQueue.front()==value)
maxQueue.pop_front();
return value;
}
deque<int> curQueue;
deque<int> maxQueue;
};
/**
* 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();
*/
时间复杂度 O(1)
空间复杂度 O(n)