One stack Simple Java solution


  • 0
    J

    When push(), compare current minimum value. If current value smaller than minimum value, push minimum value, then push minimum value and let minimum value equals current value. When pop(), if min = top, pop() twice, let minimum value equals second pop.

    public class MinStack {
    
        /** initialize your data structure here. */
        Stack<Integer> st;
        int min;
        public MinStack() {
            this.st = new Stack();
            this.min = 0;
        }
        
        public void push(int x) {
            if(st.isEmpty()) {
                st.push(x);
                min = x;
            }else if(x < min || x == min){
                st.push(min);
                st.push(x);
                min = x;
            }else{
                st.push(x);
            }
        }
        
        public void pop() {
            if(st.isEmpty()) return;
            else if(st.peek() == min){
                st.pop();
                if(!st.isEmpty()){
                   min = st.pop(); 
                }
            }else{
                st.pop();
            }
        }
        
        public int top() {
            return st.peek();
        }
        
        public int getMin() {
            return min;
        }
    }

Log in to reply
 

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