Share my C++ solution using only vector beats 100%


  • 0
    D

    The idea is to use a vector to record a pair, current number and current min in the stack.
    '''
    class MinStack {
    public:
    /** initialize your data structure here. */
    MinStack() {
    cur_min = INT_MAX;
    }

    void push(int x) {
        cur_min = min(cur_min, x);
        nums.emplace_back(x, cur_min);
    }
    
    void pop() {
        if (nums.size() == 0) return;
        nums.pop_back();
        if (nums.size() != 0) cur_min = nums.back().second;
        else cur_min = INT_MAX; // if nums get empty, reset cur_min to MAX int
    }
    
    int top() {
        return nums.back().first;
    }
    
    int getMin() {
        return cur_min;
    }
    

    private:
    vector<pair<int,int>> nums;
    int cur_min;
    };
    '''
    /


Log in to reply
 

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