LeetCode 703. The first data stream major elements K

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Oscar6280868/article/details/88892422

We first take a look at question head, found in the data stream of the K large elements:
Title Description 703
First, to get the question head, we may expect based approach to violence, it is the first data stream input is sorted, then from row good data stream in order to find the first K elements, on the line, this is a solution, we can calculate the time complexity of the solution in this case, assuming that there are N N elements, to K K elements quickly sort, then it is time complexity: O ( N K log K ) O(N \cdot K \cdot \log K) .
We have no better way to solve this problem? Here we can use thepriority queuedata structure, the role of a priority queue is to ensure that each element is taken out of the smallest weight queue (Java priority queue each taking the smallest element, C ++ taking the maximum of each priority queue element), which is achieved through the heap, specifically heap achieved through the small top complete binary tree (complete binary tree) (any of the non-leaf node weights, weight not greater than about child nodes). We can be defined as the size of the priority queue K K , are stored on top of the heap K K elements in the smallest one, when a new data stream, when it and the top of the stack smallest element is compared, is smaller than the top of the stack element, it does not put a priority queue; if the new data flow ratio top of the stack elements large, then remove the top of the stack of elements, the elements in the data stream added to the priority queue. So with the size of K K priority queue, you can guarantee the top of the stack must be the size of the K-th element. The time complexity of this time are: O ( N log K ) O(N \cdot \log K) , so that a priority queue method to solve This question is the best method. Code as follows:

class KthLargest {
    private PriorityQueue<Integer> queue;
    private int k = 0;

    public KthLargest(int k, int[] nums) {
        queue = new PriorityQueue(k);
        this.k = k;
        
        for(int i = 0; i < nums.length;i++){
            add(nums[i]);
        }
    }
    
    public int add(int val) {
        if(queue.size() < k){
            queue.offer(val);
        }else{
            if(queue.peek() < val){
            	// 踢出堆顶元素
                queue.poll();
                // 对堆顶赋值
                queue.offer(val);
            }
        }
        return queue.peek();
    }
}

Well, here I hope you help this priority queue data structure as well as its understanding of the application, thank you.

Guess you like

Origin blog.csdn.net/Oscar6280868/article/details/88892422