LeetCode Daily Question 703. The Kth Biggest Element in the Data Stream

703. The Kth largest element in the data stream

Design of the first data stream to find a kclass of large elements (class). Note that after the ordination of kmajor elements, is not the first kdifferent elements.

Please realize KthLargestcategories:

KthLargest(int k, int[] nums)Integer kand integer flow numsinitialize the object.
int add(int val)The valinsert data stream nums, the return current flow from the first klarge element.

Example:

输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]

解释:
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8

prompt:

  • 1 <= k <= 104
  • 0 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • -104 <= val <= 104
  • The add method can be called up to 104 times
  • The title data guarantees that when looking for the k-th largest element, there are at least k elements in the array

Method 1: Priority queue

Problem-solving ideas

Ideas are not important, I wish you a happy new year! !

Reference Code

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

    public KthLargest(int k, int[] nums) {
    
    
        this.queue = new PriorityQueue<>();
        this.k = k;
        for (int val : nums) {
    
    
            add(val);
        }
    }

    public int add(int val) {
    
    
        queue.offer(val);
        if (queue.size() > k) {
    
    
            queue.poll();
        }
        return queue.peek();
    }
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113791943