Source: https://leetcode.com/problems/kth-largest-element-in-an-array/

Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. You must solve it in O(n) time complexity.

/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
// O(NlogK) time, O(K) space
var findKthLargest = function(nums, k) {
// Initialize a min heap
const minHeap = new MinHeap();
nums.forEach((num) => {
minHeap.insert(num);
if (minHeap.size() > k) {
minHeap.extract();
}
});
return minHeap.peek();
};
class MinHeap {
constructor() {
this.heap = [];
}
insert(val) {
this.heap.unshift(val);
this.heap.sort((a,b) => a - b);
}
extract() {
if (this.heap.length === 0) return null;
const maxValue = this.heap.shift();
return maxValue;
}
peek() {
if (this.heap.length === 0) return null;
return this.heap[0];
}
size() {
return this.heap.length;
}
}