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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章