题解同步栈
建立一个同步栈记录最小值,当传入时是最小值就加入同步栈,不是就把之前的help[-1]即最小值加入栈。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.data=[]
self.helper=[]
def push(self, x: int) -> None:
self.data.append(x)
if len(self.helper)==0 or x<=self.helper[-1]:
self.helper.append(x)
else:
self.helper.append(self.helper[-1])
def pop(self) -> None:
if self.data:
self.helper.pop()
return self.data.pop()
def top(self) -> int:
if self.data:
return self.data[-1]
def getMin(self) -> int:
if self.helper:
return self.helper[-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.getMin()
题解2使用一个队列
关键就是要把每次最小值也加入,每次输入的是一个元组,将输入的和当前最小值都输入
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.my_stack=[]
def push(self, x: int) -> None:
if self .my_stack==[]:
self.my_stack.append((x,x))
else:
minimun=self.my_stack[-1][-1]
self.my_stack.append((x,min(x,minimun)))
def pop(self) -> None:
return self.my_stack.pop()[0]
def top(self) -> int:
return self.my_stack[-1][0]
def getMin(self) -> int:
return self.my_stack[-1][-1]