Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
  • class MinStack {
    public:
        int test[100000]={0};
        int min[100000]={0};
        int i=0,j=0;
        void push(int x) {
            if(j==0)
            {
                min[i]=x;
            }
            else
            {
                if(min[i]>=x)
                {
                    i++;
                    min[i]=x;
                }
            }
             j++;
            test[j]=x;
           
        }


        void pop() {
            if(test[j]==min[i])
            i--;
            j--;
            
        }


        int top() {
            return test[j];
        }


        int getMin() {
            return min[i];
        }
    };

人生有些关口非狠狠的斗一下不可,不能为了混口饭吃而自甘蹉跎。
原文地址:https://www.cnblogs.com/djiankuo/p/5008705.html