lgrthms
Version:
Algorithms and data structures for your JavaScript and TypeScript projects 🧑💻
54 lines (53 loc) • 1.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.findKLargest = exports.findKSmallest = void 0;
// O(nm) time | O(m) space — where
// n is the length of the array
// m is the number of elements to find
function findKSmallest(array, k, get) {
if (k === 0) {
return [];
}
if (array.length < k) {
throw new Error(`Cannot find ${k} smallest elements in array with length ${array.length}`);
}
const smallest = new Array(k).fill(null);
get = get ? get : (element) => element;
for (const element of array) {
let currentElement = element;
for (let i = 0; i < smallest.length; i++) {
const currentSmallest = smallest[i];
if (currentSmallest === null || get(currentElement) < get(currentSmallest)) {
smallest[i] = currentElement;
currentElement = currentSmallest;
}
}
}
return smallest;
}
exports.findKSmallest = findKSmallest;
// O(nm) time | O(m) space — where
// n is the length of the array
// m is the number of elements to find
function findKLargest(array, k, get) {
if (k === 0) {
return [];
}
if (array.length < k) {
throw new Error(`Cannot find ${k} largest elements in array with length ${array.length}`);
}
const largest = new Array(k).fill(null);
get = get ? get : (element) => element;
for (const element of array) {
let currentElement = element;
for (let i = 0; i < largest.length; i++) {
const currentLargest = largest[i];
if (currentLargest === null || get(currentElement) > get(currentLargest)) {
largest[i] = currentElement;
currentElement = currentLargest;
}
}
}
return largest;
}
exports.findKLargest = findKLargest;