快速实现代码:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
#申请二维数组,一维存数据,一维存当前最小值
self.stack = list()
self.topnum = -1
def push(self, x: int) -> None:
#如果当前为空,直接保存两个值
if self.topnum == -1:
self.topnum +=1
self.stack.append([x,x])
else:
#取得当前数组最小值
minnum = self.stack[self.topnum][1]
#如果输入值更小,存输入值
if minnum > x:
self.topnum += 1
self.stack.append([x,x])
else:
self.topnum +=1
self.stack.append([x,minnum])
def pop(self) -> None:
#当栈中没有元素,返回空
if self.topnum == -1:
return None
self.topnum -= 1
self.stack.pop()
def top(self) -> int:
if self.topnum == -1:
return None
res = self.stack[self.topnum][0]
return res
def min(self) -> int:
if self.topnum == -1:
return None
res = self.stack[self.topnum][1]
return res
【主要思路】使用二维数组同时记录值和状态最小值。保证时间复杂度为O(1),
此处空间复杂度为O(2n)=O(n)
【错误记录】
TypeError: 'int' object is not callable result = obj.top(); Line 70 in __helper_select_method__ (Solution.py) ret.append(__DriverSolution__().__helper_select_method__(method, params[index], obj)) Line 108 in _driver (Solution.py) _driver() Line 118 in <module> (Solution.py)
粗心:变量名和函数名没有注意区分
【深入研究】待续~