Simple C++ solution based on extra stack, Beats 97.75%


  • 0
    L
    class MinStack {
    public:
    stack<int> stk;
    stack<int> minStack;
    /** initialize your data structure here. */
    MinStack() {}
    
    void push(int x) {
       stk.push(x);
       if(minStack.size()==0 || x<=minStack.top())
            minStack.push(x);
    }
    
    void pop() {
       if(stk.top() == minStack.top())
            minStack.pop();
       stk.pop();
    }
    
    int top() {
       return stk.top();
    }
    
    int getMin() {
       return minStack.top();
    }
    };
    

Log in to reply
 

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