java arraylist & queue


  • 0
    J

    class MaxStack {
    List<Integer> list;
    Queue<Integer> queue;
    /** initialize your data structure here. */
    public MaxStack() {
    list = new ArrayList<>();
    queue = new PriorityQueue<>(10000, Collections.reverseOrder());
    }

    public void push(int x) {
        list.add(x);
        queue.offer(x);
        
    }
    
    public int pop() {
        int temp = list.remove(list.size() - 1);
        queue.remove(temp);
       return temp;
    }
    
    public int top() {
        return list.get(list.size() - 1);
    }
    
    public int peekMax() {
        return queue.peek();
    }
    
    public int popMax() {
        Integer temp = queue.poll();
        for(int i = list.size() - 1; i >= 0; i--){
            if(list.get(i).equals(temp)){
                list.remove(i);
                break;
            }
        }
         
        return (int)temp;
    }
    

    }

    /**

    • Your MaxStack object will be instantiated and called as such:
    • MaxStack obj = new MaxStack();
    • obj.push(x);
    • int param_2 = obj.pop();
    • int param_3 = obj.top();
    • int param_4 = obj.peekMax();
    • int param_5 = obj.popMax();
      */

Log in to reply
 

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