Java solution 760 ms


  • -2
    M
    class MinStack {
    
            static List<Integer> stack = new ArrayList<Integer>
            PriorityQueue<Integer> minQueue = new PriorityQueue<Integer>();
    	
    	    public void push(int x) {
    	 		
    	 		minQueue.add(x);
    	        stack.add(x);
    	    }
    
    	    public void pop() {
    	        minQueue.remove(stack.remove(stack.size() - 1));
    	  
    	    }
    
    	    public int top() {
    	    	return stack.get(stack.size() - 1);
    	    }
    
    	    public int getMin() {
    	        return minQueue.peek();
    	    }
    }

  • 0
    L

    The usage of PriorityQueue is not necessary, it makes the min-stack slow.
    Besides, using PQ makes this problem meaningless for practise.

    My solution uses only ArrayList for both stack and min.

    class MinStack {
        private ArrayList<Integer> stack;
        private ArrayList<Integer> mins;
        private int size;
        
        public MinStack() {
             stack = new ArrayList<Integer>();
             mins = new ArrayList<Integer>();
             size = 0;
        }
        
        public void push(int x) {
            stack.add(x);
            if (size==0) {
                mins.add(x);
            } else {
                int lm = mins.get(size-1);
                mins.add((x < lm) ? x : lm);
            }
            size++;
        }
    
        public void pop() {
            stack.remove(size-1);
            mins.remove(size-1);
            size--;
        }
    
        public int top() {
            return stack.get(size-1);
        }
    
        public int getMin() {
            return mins.get(size-1);
        }
    }
    

Log in to reply
 

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