Change priorityQueue to max priorityqueue

后端 未结 17 1793
一整个雨季
一整个雨季 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<Integer>  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.

    0 讨论(0)
  • 2020-12-04 05:54
    PriorityQueue<Integer> lowers = new PriorityQueue<>((o1, o2) -> -1 * o1.compareTo(o2));
    
    0 讨论(0)
  • 2020-12-04 05:55
    PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
      new Comparator<Integer> () {
        public int compare(Integer a, Integer b) {
           return b - a;
        }
      }
    );
    
    0 讨论(0)
  • 2020-12-04 05:55

    This can be achieved by the below code in Java 8 which has introduced a constructor which only takes a comparator.

    PriorityQueue<Integer> maxPriorityQ = new PriorityQueue<Integer>(Collections.reverseOrder());
    
    0 讨论(0)
  • 2020-12-04 06:00

    Here is a sample Max-Heap in Java :

    PriorityQueue<Integer> pq1= new PriorityQueue<Integer>(10, new Comparator<Integer>() {
    public int compare(Integer x, Integer y) {
    if (x < y) return 1;
    if (x > y) return -1;
    return 0;
    }
    });
    pq1.add(5);
    pq1.add(10);
    pq1.add(-1);
    System.out.println("Peek: "+pq1.peek());
    

    The output will be 10

    0 讨论(0)
  • 2020-12-04 06:00

    This can be achieved by using

    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
    
    0 讨论(0)
提交回复
热议问题