https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
题目要求访问每个函数的时间复杂度为O(1),因此不能实现遍历操作,这里引入了两个栈,另外一个栈用于存储最小值,非常妙👍

双栈法

  1. public class MinStack {
  2. Stack<Integer> s1 = new Stack<Integer>();//用于栈的push与pop
  3. Stack<Integer> s2 = new Stack<Integer>();//用于存储最小min
  4. public void push(int node) {
  5. s1.push(node);
  6. if (s2.isEmpty() || s2.peek() > node) {
  7. s2.push(node);
  8. } else {
  9. s2.push(s2.peek());
  10. }
  11. }
  12. public void pop() {
  13. s1.pop();
  14. s2.pop();
  15. }
  16. public int top() {
  17. return s1.peek();
  18. }
  19. public int min() {
  20. return s2.peek();
  21. }
  22. }