Share a solution using pq, linkedlist and JAVA built-in methods


  • 0
    T
    PriorityQueue<Integer> pq;
    LinkedList<Integer> list;
    
    /** initialize your data structure here. */
    public MaxStack() {
        pq = new PriorityQueue<>((a,b)->(b-a));
        list = new LinkedList<>();
    }
    
    public void push(int x) {
        pq.offer(x);
        list.addLast(x);
    }
    
    public int pop() {
        int pop = list.removeLast();
        pq.remove(pop);
        return pop;
    }
    
    public int top() {
        return list.getLast();
    }
    
    public int peekMax() {
        return pq.peek();
    }
    
    public int popMax() {
        int max = pq.poll();
        list.removeLastOccurrence(max);
        return max;
    }

Log in to reply
 

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