Created
April 13, 2023 21:29
-
-
Save optimistiks/06c637badca74a74295c188a37dc65f9 to your computer and use it in GitHub Desktop.
Given an infinite stream of integers, nums, design a class to find the kth largest element in a stream.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class KthLargest { | |
| // constructor to initialize heap and add values in it | |
| constructor(k, nums) { | |
| // we add all elements into the heap, and then pop until we have k elements | |
| // those k elements are k largest elements from the stream, | |
| // and the minimum of those elements is in the top of the heap, | |
| // and this is the element we need - the kth largest element | |
| const heap = new MinHeap(nums); | |
| while (heap.size() > k) { | |
| heap.poll(); | |
| } | |
| this.heap = heap; | |
| } | |
| // adds element in the heap | |
| add(val) { | |
| this.heap.offer(val); | |
| // remove element from heap to maintain heap.size === k | |
| this.heap.poll(); | |
| return this.returnKthLargest(); | |
| } | |
| // returns kth largest element from heap | |
| returnKthLargest() { | |
| return this.heap.peek(); | |
| } | |
| } | |
| export default KthLargest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
