Kth Largest Element in a Stream
EasyP2Coding
Design a class that tracks the k-th largest element in a stream of numbers. It is the k-th largest in sorted order, not the k-th distinct value.
KthLargest(k, nums)starts with the integerkand the initial elementsnums.add(val)addsvalto the stream and returns the current k-th largest element.
add is only called when the stream holds at least k elements after the insertion.
Example 1
- Input
- ["KthLargest","add","add","add","add","add"] [[3,[4,5,8,2]],[3],[5],[10],[9],[4]]
- Output
- [null,4,5,5,8,8]
Constraints
- 1 <= k <= 10^4
- 0 <= nums.length <= 10^4
- -10^4 <= nums[i], val <= 10^4
- At most 10^4 calls to add.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 5. ⌘Enter runs, ⌘⇧Enter submits.