Kth Largest Element in a Stream
EasyHeap
Design a class that tracks the k-th largest value in a stream of integers.
The k-th largest is the value at position k when all values seen so far are sorted from largest to smallest. Duplicates count as separate values, so in [8, 8, 3] the 2nd largest is 8.
Implement:
KthLargest(k, nums)initializes the object with the integerkand the starting valuesnums(which may be empty or have fewer thankvalues).add(val)appendsvalto the stream and returns the k-th largest value among all values seen so far (the initialnumsplus every value added).
Whenever add is called, the stream contains at least k values after val is appended, so an answer always exists.
The examples list the calls in order; the output shows each call's return value, with None for the constructor.
Example 1
- Input:
- KthLargest(2, [7, 1, 4]); add(5); add(2); add(9); add(8)
- Output:
- [None, 5, 5, 7, 8]
- Explanation
- With k = 2 we want the second largest. After adding 5 the values are 7, 5, 4, 1, so the answer is 5; adding 2 changes nothing. After 9 the top two are 9, 7 (answer 7), and after 8 they are 9, 8 (answer 8).
Example 2
- Input:
- KthLargest(3, [6, 6]); add(1); add(6); add(10)
- Output:
- [None, 1, 6, 6]
- Explanation
- The stream starts with only two values. After adding 1 there are exactly three, so the third largest is 1. Duplicates count separately: after adding 6 the top three are 6, 6, 6, and after 10 they are 10, 6, 6.
Example 3
- Input:
- KthLargest(1, []); add(-3); add(-5); add(2); add(2); add(-10)
- Output:
- [None, -3, -3, 2, 2, 2]
- Explanation
- With k = 1 the answer is simply the maximum seen so far.
Constraints
0 <= nums.length <= 10^41 <= k <= nums.length + 1-10^4 <= nums[i], val <= 10^4- At most
10^4calls toadd