列表

详情


剑指 Offer 59 - II. 队列的最大值

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

若队列为空,pop_frontmax_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]

 

限制:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MaxQueue { public: MaxQueue() { } int max_value() { } void push_back(int value) { } int pop_front() { } }; /** * 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(); */

python3 解法, 执行用时: 284 ms, 内存消耗: 18.8 MB, 提交时间: 2022-11-14 10:27:10

import queue
class MaxQueue:

    def __init__(self):
        self.deque = queue.deque()  # 保存排序过的队列
        self.queue = queue.Queue()

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


    def push_back(self, value: int) -> None:
        while self.deque and self.deque[-1] < value:  # 只保留>=value的元素
            self.deque.pop()
        self.deque.append(value)
        self.queue.put(value)

    def pop_front(self) -> int:
        if not self.deque:
            return -1
        ans = self.queue.get()
        if ans == self.deque[0]:
            self.deque.popleft()
        return ans


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

python3 解法, 执行用时: 176 ms, 内存消耗: 19 MB, 提交时间: 2022-11-14 10:14:29

import queue
class MaxQueue:

    def __init__(self):
        self.deque = queue.deque()

    def max_value(self) -> int:
        return max(self.deque) if self.deque else -1

    def push_back(self, value: int) -> None:
        self.deque.append(value)

    def pop_front(self) -> int:
        return self.deque.popleft() if self.deque else -1



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

python3 解法, 执行用时: 188 ms, 内存消耗: 19 MB, 提交时间: 2022-11-14 10:13:57

class MaxQueue:

    def __init__(self):
        self.arr = []


    def max_value(self) -> int:
        if len(self.arr) == 0: return -1
        return max(self.arr)


    def push_back(self, value: int) -> None:
        self.arr.append(value)


    def pop_front(self) -> int:
        if len(self.arr) == 0: return -1
        num = self.arr[0]
        self.arr = self.arr[1:]
        return num



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

上一题