703. Kth Largest Element in a Stream
Problem description:
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.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums’ length ≥ k-1 and k ≥ 1.
Solution:
In the question, it asked us to return the k
th largest element(not distinct element). To this kind of question, we can use priority_queue
to solve.
Maintain a priority_queue
, minheap, with size k
.
Whenever we push an element into queue, check if the queue size exceed k.
If it exceed k, pop out the top element(the smallest one).
example:
minheap: [], k= 3
push 4 [4]
push 5 [4,5]
push 8 [4,5,8]
push 2 [2,4,5,8], since the size of queue is 4
exceed k
, pop out the element at top.
[4,5,8]
push 3 [3,4,5,8]
[4,5,8]
push 5 [4,5,5,8]
[5,5,8]
push 10 [5,5,8,10]
[5,8,10]
1 | class KthLargest: |
1 | class KthLargest { |
time complexity: $O(nlogn)$, because the push takes $O(logn)$
space complexity: $O(1)$, because only need to keep k
elements
reference: