C++ 28ms solution, using 2 vector


  • 2

    There is no need to check whether the stack is empty or not when implementing functions like pop(). Because that is what the user is supposed to do before calling these functions.
    C++ standard library such as, vector, follows this way

    class MinStack {
    private:
        vector<int> data;
        vector<int> minHist;
    
    public:
    void push(int x) {
        data.push_back(x);
        if (minHist.empty()) minHist.push_back(x);
        else minHist.push_back(min(minHist.back(),x)); 
    }
    
    void pop() {
        data.pop_back();
        minHist.pop_back();
    }
    
    int top() {
        return data.back();
    }
    
    int getMin() {
        return minHist.back();
    }
    };

Log in to reply
 

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