Java Min Stack solution


  • 3
    V

    class MinStack {

    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();
    
    
    public void push(int x) {
        stack.push(x);
        if(minStack.isEmpty() || x <= minStack.peek()){
            minStack.push(x);
        }
    }
    
    public void pop() {
        if(stack.isEmpty()){
            return;
        }
        int x = stack.peek();
        if(!minStack.isEmpty() && x == minStack.peek()){
            minStack.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        if(minStack.isEmpty()){
            return 0;
        }
        return minStack.peek();
    }
    

    }


  • 0
    W

    In pop() function, I just use"if(!minStack.isEmpty()&&stack.peek()==minStack.peek())", then it turned wrong answer. Do you know why?


  • 0
    S

    stack.peek() and minStack.peek() return Integer types, so == compares them by reference. You need to either cast both of them to int or use stack.peek().equals(minStack.peek()) (the equals operator).

    To simplify this further (after checking whether minStack is empty or not):
    if (stack.pop().equals(minStack.peek())) minStack.pop();


  • 0
    W

    Make sense! thanks~


Log in to reply
 

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