Solution C++


  • 0
    W

    The ideia is to use a stack to keep a track for the minimum value that was pushed until now. Of course you also need to verify for the cases where the stack is empty and you need to access some value.

    class MinStack {
    public:
        /** initialize your data structure here. */
        stack<int> s;
        stack<int> mini;
        
        MinStack() {
            stack<int> emp1,emp2;
            swap(s,emp1);
            swap(s,emp2);
        }
        
        void push(int x) {
            s.push(x);
            
            if(mini.empty())
                mini.push(x);
            else
                mini.push(min(mini.top(),x));
        }
        
        void pop() {
            if(!s.empty()){
                s.pop();
                mini.pop();
            }
        }
        
        int top() {
            if(!s.empty())
                return s.top();
        }
        
        int getMin() {
            if(!mini.empty())
                return mini.top();
        }
    }
    
    

Log in to reply
 

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