题目
【代码】
执行结果:
通过
执行用时:56 ms, 在所有 Python3 提交中击败了71.14% 的用户
内存消耗:18.8 MB, 在所有 Python3 提交中击败了9.64% 的用户
通过测试用例:19 / 19
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.minstack=[]
self.minnum=[]
def push(self, x: int) -> None:
if not self.minstack:
self.minstack.append(x)
self.minnum.append(x)
else:
self.minstack.append(x)
self.minnum.append(min(x,self.minnum[-1]))
def pop(self) -> None:
self.minstack.pop()
self.minnum.pop()
def top(self) -> int:
return self.minstack[-1]
def min(self) -> int:
return self.minnum[-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.min()
【方法2】
和方法1的区别在于用于保存当前栈的最小值的辅助栈的存储最小值的方式与方法1不同,
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.minstack=[]
self.minnum=[]
def push(self, x: int) -> None:
if not self.minstack:
self.minstack.append(x)
self.minnum.append(x)
else:
self.minstack.append(x)
if x<=self.minnum[-1]:
self.minnum.append(x)
# print(self.minnum)
def pop(self) -> None:
if self.minstack[-1]==self.minnum[-1]:
self.minnum.pop()
self.minstack.pop()
def top(self) -> int:
return self.minstack[-1]
def min(self) -> int:
return self.minnum[-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.min()
【方法2简化版本】
执行用时:68 ms, 在所有 Python3 提交中击败了26.70% 的用户
内存消耗:18.5 MB, 在所有 Python3 提交中击败了37.26% 的用户
通过测试用例:19 / 19
class MinStack:
def __init__(self):
self.minstack=[]
self.minnum=[]
def push(self, x: int) -> None:
self.minstack.append(x)
if not self.minnum or x<=self.minnum[-1]:
self.minnum.append(x)
def pop(self) -> None:
if self.minstack.pop()==self.minnum[-1]:
self.minnum.pop()
def top(self) -> int:
return self.minstack[-1]
def min(self) -> int:
return self.minnum[-1]