Easy Java Solution with 2 stacks


  • 0
    E
    public class MinStack {
    
        /** initialize your data structure here. */
        public Stack<Integer>stack;
        public static int min;
        public static Stack<Integer>minstack;
        public MinStack() {
            stack=new Stack<Integer>();
            min=Integer.MAX_VALUE;
            minstack=new Stack<Integer>();
        }
        
        public void push(int x) {
            if(minstack.isEmpty() || x<=minstack.peek()){
                min=x;
                minstack.push(x);
            }
            stack.push(x);
        }
        
        public void pop() {
            int val1=stack.peek();
        	int val2=minstack.peek();
            if(val1==val2){
                minstack.pop();
            }
            stack.pop();
        }
        
        public int top() {
            return stack.peek();
         }
        
        public int getMin() {
            return minstack.peek();
        }
    }
    
    /**
     * 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.