C++ straight forward solution WITH explanation


  • 0
    U

    Basic idea: just maintain another mins stack makes this problem super easy

    class MinStack {
    public:
        stack<int> nums, mins;
    
        MinStack() {
        }
        
        void push(int x) {
            nums.push(x);
            if (mins.size())
                mins.push(min(x, mins.top()));
            else
                mins.push(x);
            return;
        }
        
        void pop() {
            nums.pop();
            mins.pop();
            return;
        }
        
        int top() {
            return nums.top();
        }
        
        int getMin() {
            return mins.top();
        }
    };
    

Log in to reply
 

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