鏡像問題(霧):Leetcode-155 最小棧
溫習deque
pop_back();//刪除容器最後一個數據
pop_front();//刪除容器第一個數據
push_back(elem);//在容器尾部添加一個數據
push_front(elem);//在容器頭部插入一個數據
pop_back();//刪除容器最後一個數據
pop_front();//刪除容器第一個數據
思路
維護正常儲存數的隊列和非遞增的單調雙端隊列,雙端隊列的頭爲最大值,維護過程類似於單調棧。
若此次新增數據的值大於以前值,以前的值沒有存在的必要,因爲新增出去的更晚,可以更長時間保持max的地位。
class MaxQueue {
public:
queue<int> que;
deque<int> maxhelp;
MaxQueue() {
}
int max_value() {
if(que.empty()) return -1;
return maxhelp.front();
}
void push_back(int value) {
que.push(value);
while(!maxhelp.empty()&&maxhelp.back()<value)
{
maxhelp.pop_back();
}
maxhelp.push_back(value);
}
int pop_front() {
if(que.empty()) return -1;
int tmp=que.front();
que.pop();
if(tmp==maxhelp.front())
maxhelp.pop_front();
return tmp;
}
};