Another Java solution - single stack but different approach


  • 0
    public class MinStack {
        class  Element {
            int num, min;
            
            public Element(int num, int min) {
                this.num = num;
                this.min = min;
            }
        }   
        
        private Deque<Element> stack;
        
        /** initialize your data structure here. */
        public MinStack() {
            stack = new ArrayDeque<>();
        }
        
        public void push(int x) {
            int cur_min = Integer.MAX_VALUE;
            
            if(!stack.isEmpty()) {
                cur_min = stack.peek().min;
            }
            
            stack.push(new Element(x, Math.min(x, cur_min)));
    
        }
        
        public void pop() {
            stack.pop();  
        }
        
        public int top() {
            return stack.peek().num;
        }
        
        public int getMin() {
            return stack.peek().min;
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    

Log in to reply
 

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