【剑指Offer】面试题59 - II. 队列的最大值(c++)

题目

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

解题思路

使用一个双向链表辅助,保存最大值序列
Note:链表中小于后插入的元素的元素,对结果没有影响

代码

class MaxQueue {
    
    
private:
    queue<int> que;
    list<int> que_vice;
public:
    MaxQueue() {
    
    
    }
    
    int max_value() {
    
    
    //    cout<<"max:"<<que_vice.front()<<endl;
        if(que.empty()){
    
    
            return -1;
        }
        return que_vice.front();
    }
    
    void push_back(int value) {
    
    
    //    cout<<"pus:"<<value<<endl;
        if(value > que_vice.front()){
    
     // 大于最大元素
            que_vice.clear();
            que_vice.push_back(value);
        }else{
    
     
            // 移除所有小于当前插入元素的结点
            while(que_vice.back() < value){
    
    
            	que_vice.pop_back();
            }
            que_vice.push_back(value);
        }
        que.push(value);
    }
    
    int pop_front() {
    
    
        
        if(que.empty()){
    
    
            return -1;
        }
        int t = que.front();
        que.pop();
        if(t == que_vice.front()){
    
    
            que_vice.pop_front();
        }
    //    cout<<"pop:"<<t<<endl;
        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();
 */

时间复杂度

https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/solution/mian-shi-ti-59-ii-dui-lie-de-zui-da-zhi-by-leetcod/273110

猜你喜欢

转载自blog.csdn.net/Activity_Time/article/details/104718748
今日推荐