Deep understanding of Java PriorityQueue

The github address of this article

PriorityQueue in Java is implemented by a binary small top heap, which can be represented by a complete binary tree. This article starts from the Queue interface function, combined with vivid diagrams, analyzes the specific process and time complexity of each operation of PriorityQueue in simple language, and will allow readers to establish a clear and in-depth understanding of PriorityQueue.

General introduction

The Java  ArrayDeque was used as an example to explain Stack and Queue . In fact, there is a special queue called PriorityQueue , which is a priority queue. The function of the priority queue is to ensure that the elements taken out each time have the smallest weight in the queue (the Java priority queue takes the smallest element each time, and the C++ priority queue takes the largest element each time). The size relationship is involved here. The size of the element can be judged by the natural ordering of the element itself, or by the comparator ( Comparator , similar to the C++ functor) passed in during construction .

PriorityQueue in Java implements the Queue interface and does not allow nullelements; it is implemented by heap, specifically a small top heap implemented by a complete binary tree (the weight of any non-leaf node is not greater than its left and right sides). The weight of the child node), which means that an array can be used as the underlying implementation of PriorityQueue .

 

 

http://www.cnblogs.com/CarpenterLee/p/5488070.html

 

public class KthLargeInArray {

    public static void main(String[] args) {
        
        System.out.println(findKthLargest(new int[]{1,9,5,4,3}, 1));

    }
    public static int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(k);
        for(int i: nums){
            q.offer(i);
     
            if(q.size()>k){
                System.out.println("q: " + q.poll());
            }
        }
     
        return q.peek();
    }
}

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992299&siteId=291194637