Is this a viable alternative to the K Closest number problem? It is a lot more simple, and I dont think it really affects run time, at least in the worst case.
const find_closest_elements = function (arr, K, X) {
const maxHeap = new Heap([], null, ((a, b) => a[0] - b[0]));
for (let i = 0; i < arr.length; i++) {
maxHeap.push([Math.abs(X - arr[i]), arr[i]]);
if (maxHeap.length > K)
maxHeap.pop();
}
let result = [];
let maxHeapLength = maxHeap.length;
for (let i = 0; i < maxHeapLength; i++){
result.push(maxHeap.pop()[1]);
}
return result;
};
console.log(`'K' closest numbers to 'X' are: ${find_closest_elements([5, 6, 7, 8, 9], 3, 7)}`)
console.log(`'K' closest numbers to 'X' are: ${find_closest_elements([2, 4, 5, 6, 9], 3, 6)}`)
console.log(`'K' closest numbers to 'X' are: ${find_closest_elements([2, 4, 5, 6, 9], 3, 10)}`)