Problem
Design a class to find the kth
largest element in a stream. Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
Implement KthLargest
class:
KthLargest(int k, int[] nums)
Initializes the object with the integerk
and the stream of integersnums
.int add(int val)
Appends the integerval
to the stream and returns the element representing thekth
largest element in the stream.
Class Skeleton:
|
|
Examples
Example 1:
|
|
Solution
Method 1 - Using minHeap
What we can do is store the k largest elements in the heap. When we find element larger that root of minHeap, we will remove that element and add current element to heap.
Video Explanation
Here is the video explanation of the same:
Code
|
|
|
|
|
|