Clean C++ solution with ONE Stack


  • 0
    B
    #include<algorithm>
    #include<stack>
    
    class MinStack {
    public:
    
        
        stack<int> s;
    
        MinStack() {
            
        }
        
        void push(int x) {
            
            if(s.size() == 0)
            {
                s.push(x);
                s.push(x);
            }
            else
            {
                int m= s.top();
                s.push(x);
                s.push(min(x,m));
            }
        }
        
        void pop() {
            s.pop();
            s.pop();
        }
        
        int top() {
            int m=s.top();
            s.pop();
            int ans=s.top();
            s.push(m);
            return ans;
        }
        
        int getMin() {
            return  s.top();
        }
    };
    

Log in to reply
 

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