Created
April 17, 2023 13:29
-
-
Save optimistiks/fa95c4e98d75b0fc6f7d88bd2721539a to your computer and use it in GitHub Desktop.
Find the kth largest element in an unsorted array.
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
| export function findKthLargest(arr, k) { | |
| // we are going to have min heap of size k | |
| // it means the top of the heap is going to be the minimum element | |
| // of all k elements in the heap | |
| // which is exactly the kth largest element that we need | |
| const heap = new MinHeap(); | |
| for (let i = 0; i < k; ++i) { | |
| // initialize the heap with the first k elements from the array | |
| heap.offer(arr[i]); | |
| } | |
| for (let i = k; i < arr.length; ++i) { | |
| // iterate the rest of the array | |
| if (arr[i] > heap.peek()) { | |
| // if array element is larger than the top of the heap, | |
| // it means top of the heap is not part of the k largest elements, | |
| // so we remove it, and push the current element to the heap | |
| heap.poll(); | |
| heap.offer(arr[i]); | |
| } | |
| } | |
| // top of the min heap is the kth largest element | |
| return heap.peek(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
