剑指offer

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

2020-07-21  本文已影响0人  人一己千

题目

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

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

示例 1:

输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:

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

限制:

1 <= push_back,pop_front,max_value的总操作数 <= 10000
1 <= value <= 10^5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

跟栈的思路类似,
队列的话只能先进先出,也就是说,给一个超大的值,如果这个值没有出队列,那么前面的那些值就都没有意义。只有后面比他小的可以在他离开之后顶起一片天。
也就是说,要维护一个单调递减的队列!
这里要注意,新来一个比较小的数之后,要把一些数字从右边排除掉。

代码

class MaxQueue:

    def __init__(self):
        self.queue = []
        self.aux = []

    def max_value(self) -> int:
        if self.aux:
            return self.aux[0]
        else:
            return -1

    def push_back(self, value: int) -> None:
        self.queue.append(value)
        # if len(self.aux) == 0 or self.aux[-1] > value:
        #     self.aux.append(value)
        # else:
        #     if self.aux[0] < value: self.aux = [value]
        #     else:
        #         while self.aux[-1] < value:
        #             self.aux = self.aux[:-1]
        #         self.aux.append(value)
        while self.aux and self.aux[-1] < value:
            self.aux.pop()
        self.aux.append(value)


    def pop_front(self) -> int:
        if len(self.queue) == 0:
            return -1
        value = self.queue[0]
        self.queue = self.queue[1:]
        if value == self.aux[0]:
            self.aux = self.aux[1:]
        return value



# Your MaxQueue object will be instantiated and called as such:
# obj = MaxQueue()
# param_1 = obj.max_value()
# obj.push_back(value)
# param_3 = obj.pop_front()
上一篇下一篇

猜你喜欢

热点阅读