Share my C++ solution with only one stack of pair.


  • 0
    Y

    How about this?

    class MinStack {
    private:
        stack<pair<int, int>> s;
        int min = INT_MAX;
    
    public:
        void push(int x) {
            min = x <= min ? x : min; 
            s.push(make_pair(x, min));
        }
    
        void pop() {
            s.pop();
            min = s.size() > 0 ? s.top().second : INT_MAX;
        }
        
        int top() {
            return s.size() > 0 ? s.top().first : 0;
        }
        
        int getMin() {
            return s.size() > 0 ? min : 0;
        }
    };
    

Log in to reply
 

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