题目要求实现四个函数,分别是push,pop,top,min,并且要求min的时间复杂度为1
我们在以往经验得出想要获取最小值的排序并没有时间复杂度为1的算法,
因此想要实现时间复杂度为1只能牺牲空间,边入栈出栈的时候保存最小值,而此时如果使用空间复杂度为1的变量保存在出栈时无法得到上一个最小值,因此使用辅助栈。
在入栈时如果辅助栈内无元素或者辅助栈顶元素大于等于当前需要入栈的值,则将此值入辅助栈(保证辅助栈内永远是最小值在栈顶并且排序严格降序)
在出栈时对比辅助栈和出栈元素是否一样,一样则辅助栈也出栈一个元素。
代码:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1,self.stack2 = [],[]
self.minstack = None
def push(self, x: int) -> None:
self.stack1.append(x)
if self.stack2 == [] or self.stack2[-1] >= x:
self.stack2.append(x)
def pop(self) -> None:
x = self.stack1.pop()
if self.stack2[-1] == x:
self.stack2.pop()
return x
def top(self) -> int:
return self.stack1[-1]
def min(self) -> int:
if self.stack2: return self.stack2[-1]
时间复杂度99