Java solution using another stack for minimums at each level, beats 96%


  • 0
    M
    public class MinStack {
    
        /** initialize your data structure here. */
        private Stack<Integer> mainStack;
        private Stack<Integer> stackForMins;
        public MinStack() {
            mainStack = new Stack<>();
            stackForMins = new Stack<>();
        }
        
        public void push(int x) {
            if(stackForMins.isEmpty()){
                stackForMins.push(x);
            }
            else{
                stackForMins.push(Math.min(stackForMins.peek(), x));
            }
            mainStack.push(x);
        }
        
        public void pop() {
            if(!mainStack.isEmpty()){
                int x = mainStack.pop();
                stackForMins.pop();
            }
        }
        
        public int top() {
            return mainStack.peek();
        }
        
        public int getMin() {
            return stackForMins.peek();
        }
    }
    

Log in to reply
 

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