剑指 Offer 30. 包含min函数的栈:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
解题思路:
利用辅助栈保存当前栈中最小值
class MinStack:
def __init__(self):
self.stack = []
self.aux = []
def push(self, x: int) -> None:
if len(self.aux)==0 or self.aux[-1]>=x: #辅助栈顶值>=新元素
self.aux.append(x)
self.stack.append(x)
def pop(self) -> None:
if len(self.aux)!=0 and self.stack[-1]==self.aux[-1]:
self.aux.pop()
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
return self.aux[-1]
细节注意:
对相同的最小值依然需要存到辅助栈中
持续更新中……