剑指Offer:队列最大值

 

队列最大值

 

题目

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -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

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

# 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()

思路

本题的难点在于如何快速求取max,那么问题的关键就在于如何维护一个队列的有序性,使得其能够随时调用最大值。
暴力解法(遍历求解)不可取
这里利用import queue来调用队列,但本题利用两个list即可完成pop,push和max

解法

class MaxQueue:
    def __init__(self):
        self.A = []#存储队列
        self.B = []#最大值队列

    def max_value(self) -> int:
    #返回最大值队列的第一个元素
        if self.B:return self.B[0]
        else:return -1
        
    def push_back(self, value: int) -> None:
    #A直接插入,B中需要比较队列中的最后一个元素,
    #如果最后一个元素比value小就pop,否则插入
    #从而达到维护B为单调递减队列
        self.A.append(value)
        while self.B and self.B[-1]<value:
            self.B.pop()
        self.B.append(value)

    def pop_front(self) -> int:
    #按照题目要求,没有值就return -1,有值的情况下
    #return A[0],而此时如果pop的是最大元素,则B中
    #的首元素也要pop掉
        if not self.A:
            return -1
        else:
            ans = self.A.pop(0)
            if ans==self.B[0]:
                self.B.pop(0)
            return ans


posted @ 2020-07-28 18:35  okmonkey  阅读(28)  评论(0)    收藏  举报