Simple Java solution (one stack)


  • 0
    C

    A simple solution using one stack storing "Node" object. The concept is to store the current min value on each node. When a node becomes the top node of the stack, the min value of current stack is stored on the top node.

    class MinStack {
        Stack<Node> stack;
      
        public MinStack() {
            stack = new Stack<Node>();    
        }
        
        public void push(int x) {
            int currMin = (stack.isEmpty())? x : stack.peek().min;
            currMin = Math.min(currMin, x);        
            stack.push(new Node(x, currMin));
        }
        
        public void pop() {
            if(!stack.isEmpty()){
                stack.pop();        
            }
        }
        
        public int top() {
            if(!stack.isEmpty()){
                return stack.peek().val;
            }else return 0;
        }
        
        public int getMin() {
            if(!stack.isEmpty()){
               return stack.peek().min;         
            }else return 0;
        }
        
        private class Node{
            int min, val;
            Node(int v, int m){
                this.min = m;
                this.val = v;
            }
        }
    }
    

Log in to reply
 

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