【剑指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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值