思路:用辅助栈来存动态的最小值,pop时弹出栈顶的最小值即可。
Python:
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack=[] self.helpstack=[] def push(self, x: int) -> None: self.stack.append(x) if not self.helpstack or x<self.helpstack[-1]: self.helpstack.append(x) else: self.helpstack.append(self.helpstack[-1]) def pop(self) -> None: self.stack.pop() self.helpstack.pop() def top(self) -> int: if self.stack: return self.stack[-1] else: return -1 def min(self) -> int: if not self.helpstack: return -1 else: return self.helpstack[-1]