- 运用辅助栈,它只添加当前的最小值。
- 外部调用push函数过程中不断更新当前的最小值。
import sys
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [sys.maxsize] # 辅助栈
self.min = self.min_stack[-1]
def push(self, val: int) -> None:
self.stack.append(val)
self.min = min(self.min, val) # 更新最小值
self.min_stack.append(self.min) # 辅助栈只添加当前的最小值
def pop(self) -> None:
# 两个栈同时pop以保持同步
self.stack.pop()
self.min_stack.pop()
self.min = self.min_stack[-1] # pop后一定要及时更新最小值
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()