面试题59 - II. 队列的最大值(Leetcode每日一题-2020.03.07)

Problem

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。

若队列为空,pop_front 和 max_value 需要返回 -1

Example1

输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]

Example2

输入:
[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]
输出: [null,-1,-1]

Solution

2020-3-7,本题没有什么思路,参考了题解。
使用两个双端队列,作为底层存储结构。
deque1用来存储队列的数据;
deque2用于维护一个单调递减的序列

  • 新元素入队列时,从deque2的队尾向前依次与新元素比较,如果遍历到的元素小于新元素,就将它出队。因为对这些被出队的元素来说,当它们位于队首时,最大值是新元素。
  • 当要pop_front时,deque1从队首出队,如果出队元素与deque2的队首元素相同,也将deque2从队首出队。
  • 需要max_value时,直接返回deque2的队首或者-1.
class MaxQueue {
    deque<int> q1;
    deque<int> q2;
public:
    MaxQueue() {
        q1.clear();
        q2.clear();


    }
    
    int max_value() {
        if(q2.empty())
            return -1;
        return q2.front();

    }
    
    void push_back(int value) {
        q1.push_back(value);
        while(!q2.empty() && q2.back() < value)
        {
            q2.pop_back();
        }
        q2.push_back(value);


    }
    
    int pop_front() {
        if(q1.empty())
            return -1;
        else
        {
            int ret = q1.front();
            q1.pop_front();
            if(ret == q2.front())
            {
                q2.pop_front();
            }
            return ret;
        }
    }
};

/**
 * 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();
 */
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104723363