703 Kth Largest Element in a Stream. This Java class, KthLargest, is designed to find the k-th largest element in a stream of numbers.
Here's a simplified explanation:
1. Instance Variables:
PriorityQueue pq: A min-heap to store the k largest elements.
int k: The k-th position we are interested in.
2. Constructor (KthLargest(int k, int[] nums)):
Initializes the priority queue with a capacity of k.
Adds each number from the input array nums to the priority queue using the add method.
3. Method (add(int val)):
Adds a new number val to the priority queue.
If the queue has fewer than k elements, it simply adds the new number.
If the queue already has k elements and the new number is larger than the smallest element in the queue (the root of the min-heap), it removes the smallest element and adds the new number.
Returns the smallest element in the priority queue, which is the k-th largest element in the current set of numbers.
In summary, the class maintains the k largest elements seen so far in a min-heap, and the smallest element in this heap is the k-th largest overall.
Негізгі бет 703 Kth Largest Element in a Stream
Пікірлер