Java solution without stack


  • 0
    M

    Use a class Tuple to record the current minimum value.

    public class MinStack {
        private List<Tuple> list;
        private int min = Integer.MAX_VALUE;
        /** initialize your data structure here. */
        public MinStack() {
            list = new ArrayList<>();
        }
        
        public void push(int x) {
            if(x<min) min = x;
            list.add(new Tuple(x, min));
        }
        
        public void pop() {
            list.remove(list.size()-1);
            if(list.isEmpty()) min = Integer.MAX_VALUE;
            else min = list.get(list.size()-1).min;
        }
        
        public int top() {
            return list.get(list.size()-1).val;
        }
        
        public int getMin() {
            return list.get(list.size()-1).min;
        }
        
        class Tuple{
            int val;
            int min;
            Tuple(int val, int min){
                this.val = val;
                this.min = min;
            }
        }
    }
    

Log in to reply
 

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