My easy to understand Java solution


  • 0
    W

    It's just a direct use of java Stack class, except remember the min so far and wrapped into a node with every value pushed.

    class MinStack {
        private class Node {
            int val;
            int min;
            public Node(int x) {
                val = x;
                min = x;
            }
            public Node(int x, int minSoFar) {
                val = x;
                min = minSoFar;
            }
        }
        
        /** initialize your data structure here. */
        Stack<Node> stack;
        public MinStack() {
            stack = new Stack<Node>();
        }
        
        public void push(int x) {
            int min = x;
            if (!stack.isEmpty()) {
                min = Math.min(x, stack.peek().min);
            }
            Node node = new Node(x, min);
            stack.push(node);
        }
        
        public void pop() {
            stack.pop();
        }
        
        public int top() {
            return stack.peek().val;
        }
        
        public int getMin() {
            return stack.peek().min;
        }
    }
    

Log in to reply
 

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