请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
解法1:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.l = []
self.l1 = []
def push(self, x: int) -> None:
self.l.append(x)
if not self.l1 or x <= self.l1[-1]:
self.l1.append(x)
def pop(self) -> None:
x = self.l.pop()
if x == self.l1[-1]:
self.l1.pop()
def top(self) -> int:
return self.l[-1]
def getMin(self) -> int:
return self.l1[-1]
【leetcode-python】面试题 03.02. 栈的最小值
最新推荐文章于 2022-05-10 16:11:18 发布