Java solution using two Stack


  • 1
    W
    class MinStack {
    	Stack<Integer> stack;
    	Stack<Integer> minStack;
    
    	MinStack() {
    		stack = new Stack<Integer>();
    		minStack = new Stack<Integer>();
    	}
    	
    	
        public void push(int x) {
            stack.push(new Integer(x));
            if(minStack.isEmpty()||x<=minStack.peek()){
            	minStack.push(new Integer(x));
            	}
        }
    
        public void pop() {
        	if(stack.peek().equals(minStack.peek())){ // notice that stack.peek() returns an referrence of object, and can't be compared using "=="
        	
        		minStack.pop();
        	}
            stack.pop();
        }
    
    	public int top() {
    		int result = stack.peek();
    		return result;
    	}
       
    
        public int getMin() {
        	
        	return minStack.peek();
            
        }
    }

Log in to reply
 

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