剑指OFFER----面试题59 - II. 队列的最大值

链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

代码

class MaxQueue {
public:
    queue<int> q;
    deque<int> d;
    MaxQueue() {

    }
    
    int max_value() {
        if (d.empty()) return -1;
        return d.front();
    }
    
    void push_back(int value) {
        while (!d.empty() && d.back() < value) d.pop_back();
        d.push_back(value);
        q.push(value);
    }
    
    int pop_front() {
        if (q.empty()) return -1;
        int ans = q.front();
        if (ans == d.front()) d.pop_front();
        q.pop();
        return ans;
    }
};

/**
 * 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();
 */
posted @ 2020-03-12 21:17  景云ⁿ  阅读(55)  评论(0编辑  收藏  举报