题目

image.png
image.png
提示:

  • poptopgetMin 操作总是在 非空栈 上调用。

思路

要在常数时间内获得当前栈的做小元素,那么只能申请一个额外的辅助栈aux_stack,保存当前栈的最小值。

  1. class MinStack:
  2. def __init__(self):
  3. """
  4. initialize your data structure here.
  5. """
  6. self.stack = []
  7. self.aux_stack = []
  8. def push(self, x: int) -> None:
  9. self.stack.append(x)
  10. if not self.aux_stack or x <= self.aux_stack[-1]:
  11. self.aux_stack.append(x)
  12. def pop(self) -> None:
  13. if self.stack.pop() <= self.aux_stack[-1]:
  14. self.aux_stack.pop()
  15. def top(self) -> int:
  16. return self.stack[-1]
  17. def getMin(self) -> int:
  18. return self.aux_stack[-1]