C++ solution using two stacks (better than 84.93% c++ submission)


  • 0
    M
    class MinStack {
    public:
        /** initialize your data structure here. */
        stack<int> main_stack;
        stack<int> auxi_stack;
        
        MinStack() {
    
        }
        
        void push(int x) {
            if(auxi_stack.empty()){
                auxi_stack.push(x);
                main_stack.push(x);
            }else{
                if(x <= auxi_stack.top()){
                    auxi_stack.push(x);
                }
                main_stack.push(x);
            }
        }
        
        void pop() {
            if(!main_stack.empty()){
                if(main_stack.top() == auxi_stack.top()){
                    auxi_stack.pop();
                }
                main_stack.pop();
            }
        }
        
        int top() {
            return main_stack.top();
        }
        
        int getMin() {
            return auxi_stack.top();
        }
    };
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    

Log in to reply
 

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