My Java solution, using 2 stacks.


  • 3
    D
    import java.util.Stack;
    

    class MinStack {
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();

    public void push(int x) {
        stack.push(x);
        if (minStack.isEmpty() || x <= minStack.peek()) {
            minStack.push(x);
        }
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            int x = stack.pop();
            if (x == minStack.peek()) {
                minStack.pop();
            }
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
    

    }


  • 0
    S

    you use stack to create another stack? I though we should use list or array


  • 0
    K

    Min Stack is another data structure.However it is implemented is not cared.It is like that you implement a common stack with an array


Log in to reply
 

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