Design a class that returns the kth largest value of a growing stream. KthLargest(k, nums) starts the stream; add(val) appends val and returns the current kth largest. Input is a LeetCode-style list of operations.
Keep only the k largest values in a min-heap. Its smallest element is exactly the kth largest overall; anything smaller can be thrown away.
1class KthLargest {2heap = new MinPriorityQueue<number>();3constructor(private k: number, nums: number[]) {4for (const x of nums) this.add(x);5}6add(val: number): number {7this.heap.enqueue(val);8if (this.heap.size() > this.k) this.heap.dequeue();9return this.heap.front()!;10}11}
k = 3. Add the initial values.
Space: play/pause · ←/→: step