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

题意

求队列的最大值

方法

单调队列

代码

class MaxQueue {
public:
    int q[100010] = {0};
    int s[100010] = {0};
    int k, t, l, r;
    MaxQueue() {
        k = -1;
        t = 0;
        r = -1;
        l = 0;
    }
    
    int max_value() {
        if (k < t) return -1;
        while (l <= r && s[l] < t) l++;
        return q[s[l]];
    }
    
    void push_back(int value) {
        q[++k] = value;
        while (l <= r && q[k] > q[s[r]]) r--;
            s[++r] = k;
    }
    
    int pop_front() {
        if (k < t) return -1;
        return q[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();
 */

你可能感兴趣的:(算法,数据结构)