My c++ code (push both x and the old minVal to the stack when x is no larger than the current minVal)


  • 0
    D

    The basic idea is not new and has been posted by other programmers: (push both x and the old minVal to the stack when x is no larger than the current minVal)
    private:
    stack<int> inStack;
    int minVal;

    class MinStack {
    private:    
        stack<int> inStack;
        int minVal;
    public:
        void push(int x) {
            if( (inStack.empty()) || (x<=minVal) )
            {
                inStack.push(minVal);
                minVal = x;
            }
            inStack.push(x);
        }
    
        void pop() {
            int x;
            if( !(inStack.empty()) )
            {
                x= inStack.top();
                inStack.pop();
                if(x<= minVal)
                {
                    minVal = inStack.top();
                    inStack.pop();
                }
            }
        }
    
        int top() {
            if(inStack.empty())
            {
                return 0;
            }
            else
            {
                return inStack.top();
            }
        }
    
        int getMin() {
            return minVal;
        }
        
    };

Log in to reply
 

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