C++ simple one stack solution


  • 1
    C

    Use pair to combine x and min together.

    class MinStack {
        stack<pair<int, int>> s;
    public: 
        void push(int x) {
            s.emplace(x, s.empty() ? x : min(x, getMin()));
        }
        void pop() {
            s.pop();
        }
        int top() {
            return s.top().first;
        }
        int getMin() {
            return s.top().second;
        }
    };
    

Log in to reply
 

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