Change priorityQueue to max priorityqueue

后端 未结 17 1843
一整个雨季
一整个雨季 2020-12-04 05:13

I have priority queue in Java of Integers:

 PriorityQueue pq= new PriorityQueue();

When I call pq.poll(

17条回答
  •  佛祖请我去吃肉
    2020-12-04 05:53

    You can try pushing elements with reverse sign. Eg: To add a=2 & b=5 and then poll b=5.

    PriorityQueue  pq = new PriorityQueue<>();
    pq.add(-a);
    pq.add(-b);
    System.out.print(-pq.poll());
    

    Once you poll the head of the queue, reverse the sign for your usage. This will print 5 (larger element). Can be used in naive implementations. Definitely not a reliable fix. I don't recommend it.

提交回复
热议问题