Please define a queue and implement the function max_value to get the maximum value in the queue. The amortized time complexity of functions max_value, push_back and pop_front are all O(1).
If the queue is empty, pop_front and max_value need to return -1
Example 1:
Input:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
Output: [null,null,null,2,1,2]
Example 2:
Input:
["MaxQueue","pop_front","max_value"]
[[],[],[]]
Output: [null,-1,-1]
limit:
1 <= push_back,pop_front,max_value的总操作数 <= 10000
1 <= value <= 10^5
Like the previous question, create an auxiliary two-way queue to save the maximum value.
class MaxQueue {
public:
queue<int>q;
deque<int>de;
MaxQueue() {
}
int max_value() {
if(q.empty()) return -1;
return de.front();
}
void push_back(int value) {
q.push(value);
while((!de.empty())&&de.back()<value) de.pop_back();
de.push_back(value);
}
int pop_front() {
if(q.empty()) return -1;
if(de.front()==q.front()) de.pop_front();
int t=q.front();
q.pop();
return t;
}
};
/**
* 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();
*/