Using LinkedList and PriorityQueue


  • 0
    N
    List<Integer> list; 
    PriorityQueue<Integer> pq;
    int top = -1;
    
    public MinStack() {
        list = new ArrayList<>();
        pq = new PriorityQueue<>( (a,b)-> (Integer.compare(a, b)));
    }
    
    public void push(int x) {   
        list.add(x);
        top++;
        pq.add(x);   
    }
    
    public void pop() {    
        if(list.size()!=0){          
          pq.remove(list.get(top));
          list.remove(top--);
        }
    }
    
    public int top() {     
        if(list.size()!=0){
            return list.get(top);
        } 
            return Integer.MIN_VALUE;
    }
    
    public int getMin() {  
            return pq.peek();
    }

Log in to reply
 

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