定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minvalue = []
def push(self, x: int) -> None:
if self.stack == []:
self.minvalue.append(x)
elif x <= self.minvalue[-1]:
self.minvalue.append(x)
self.stack.append(x)
def pop(self) -> None:
if self.stack.pop() == self.minvalue[-1]:
self.minvalue.pop()
# 这样写如果stack=[],self.stack[-1]可能会出现索引超出范围的问题
# if self.stack[-1] == self.minvalue[-1]:
# self.minvalue.pop()
# self.minvalue.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
return self.minvalue[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
执行用时:52 ms, 在所有 Python3 提交中击败了75.89% 的用户
内存消耗:18.4 MB, 在所有 Python3 提交中击败了12.68% 的用户
通过测试用例:19 / 19