C++ simple solution


  • 4
    X
    class MinStack {
    public:
        stack<int> st;
        stack<int> nextMin;
        
        void push(int x) {
            if(st.empty()){
                nextMin.push(x);
            }else if(nextMin.top() >= x){
                nextMin.push(x);
            }
            st.push(x);
        }
    
        void pop() {
            int tmp = st.top();
            st.pop();
            if(tmp == nextMin.top()){
                nextMin.pop();
            }
        }
    
        int top() {
            return st.top();
        }
    
        int getMin() {
            return nextMin.top();
        }
    };

Log in to reply
 

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