题目链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
难度:简单

描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

题解

  1. class MinStack:
  2. def __init__(self):
  3. """
  4. initialize your data structure here.
  5. """
  6. self.stk = []
  7. self.min_stk = []
  8. def push(self, x: int) -> None:
  9. self.stk.append(x)
  10. if self.min_stk == []:
  11. self.min_stk.append(x)
  12. else:
  13. if x < self.min_stk[-1]:
  14. self.min_stk.append(x)
  15. else:
  16. self.min_stk.append(self.min_stk[-1])
  17. def pop(self) -> None:
  18. self.stk.pop()
  19. self.min_stk.pop()
  20. def top(self) -> int:
  21. return self.stk[-1]
  22. def min(self) -> int:
  23. return self.min_stk[-1]