Cpp solution using 2 stacks


  • 0
    P
    class MinStack {
        stack<int> numsStk;/**using 2 stacks*/
        stack<int> minStk;
    public:
        /** initialize your data structure here. */
        MinStack() {
            return;
        }
        void push(int x) {
            if(numsStk.empty()){
                numsStk.push(x);
                minStk.push(x);
            }
            else{
                if(x<=minStk.top()){
                    minStk.push(x);
                }
                numsStk.push(x);
            }
            return;
        }
        void pop() {
            if(minStk.top()==numsStk.top()) minStk.pop();
            numsStk.pop();
            return;
        }
        int top() {
            return numsStk.top();
        }
        int getMin() {
            return minStk.top();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.