class Solution:
def __init__(self):
self.stack=[]
self.minstack=[]
def push(self, node):
# write code here
self.stack.append(node)
if not self.minstack or (self.minstack and self.minstack[-1]>node):
self.minstack.append(node)
else:
self.minstack.append(self.minstack[-1])
def pop(self):
# write code here
self.minstack.pop()
return self.stack.pop()
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.minstack[-1]
我的算法之路44--包含min函数的栈
本文介绍了一种使用双栈实现的高效数据结构,能够在O(1)时间内获取当前栈内的最小值,同时支持push、pop、top等常见操作。通过维护两个栈,一个用于存储数据元素,另一个用于跟踪最小值,确保了在进行各种操作的同时,能够快速找到最小元素。

被折叠的 条评论
为什么被折叠?



