最小栈

 

 

 

当一个元素要入栈时,我们取当前辅助栈的栈顶存储的最小值,与当前元素比较得出最小值,将这个最小值插入辅助栈中(min_stack.push(min(x,min_stack.top()))

当一个元素要出栈时,我们把辅助栈的栈顶元素也一并弹出;

在任意一个时刻,栈内元素的最小值就存储在辅助栈的栈顶元素中。

 

class MinStack {
      stack<int> x_stack;
      stack<int> min_stack;
  public:
      MinStack() {
          min_stack.push(INT_MAX);
      }

      void push(int x) {
          x_stack.push(x);
          min_stack.push(min(min_stack.top(), x));
      }

      void pop() {
          x_stack.pop();
          min_stack.pop();
      }

      int top() {
          return x_stack.top();
      }

      int getMin() {
          return min_stack.top();
      }
  };

 

posted @ 2020-05-13 15:11  知道了呀~  阅读(221)  评论(0编辑  收藏  举报