定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
1、方法一:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.li = []
self.li2 = []
def push(self, x: int) -> None:
self.li.append(x)
if not self.li2 or x <= self.li2[-1]:
self.li2.append(x)
def pop(self) -> None:
if self.li[-1] == self.li2[-1]:
self.li2.pop()
self.li.pop()
def top(self) -> int:
return self.li[-1]
def min(self) -> int:
return self.li2[-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()