跳到主要内容

面试题17.14.最小K个数

链接:面试题17.14.最小K个数
难度:Medium
标签:数组、分治、快速选择、排序、堆(优先队列)
简介:设计一个算法,找出数组中最小的 k 个数。以任意顺序返回这 k 个数均可。

题解 1 - typescript

  • 编辑时间:2021-05-07
  • 执行用时:164ms
  • 内存消耗:45.1MB
  • 编程语言:typescript
  • 解法介绍:利用内部排序。
function smallestK(arr: number[], k: number): number[] {
return arr.sort((a, b) => a - b).slice(0, k);
}

题解 2 - typescript

  • 编辑时间:2021-09-03
  • 执行用时:8000ms
  • 内存消耗:48.4MB
  • 编程语言:typescript
  • 解法介绍:堆。
class Heap<T = number> {
private arr: T[] = [];
get isEmpty() {
return this.size === 0;
}
get size() {
return this.arr.length;
}
get top() {
return this.arr[0];
}
constructor(private compare: (t1: T, t2: T) => number) {}
add(num: T): void {
this.arr.push(num);
this.shiftUp(this.size - 1);
}
remove(): T {
const num = this.arr.shift()!;
if (this.size) {
this.arr.unshift(this.arr.pop()!);
this.shiftDown(0);
}
return num;
}
private shiftUp(index: number): void {
if (index === 0) return;
const parentIndex = (index - 1) >> 1;
if (this.compare(this.arr[index], this.arr[parentIndex]) > 0) {
[this.arr[index], this.arr[parentIndex]] = [this.arr[parentIndex], this.arr[index]];
this.shiftUp(parentIndex);
}
}
private shiftDown(index: number): void {
let childrenIndex = index * 2 + 1;
if (childrenIndex > this.size - 1) return;
if (
childrenIndex + 1 <= this.size - 1 &&
this.compare(this.arr[childrenIndex + 1], this.arr[childrenIndex]) > 0
) {
childrenIndex++;
}
if (this.compare(this.arr[childrenIndex], this.arr[index]) > 0) {
[this.arr[childrenIndex], this.arr[index]] = [this.arr[index], this.arr[childrenIndex]];
this.shiftDown(childrenIndex);
}
}
*[Symbol.iterator](): IterableIterator<T> {
for (const t of this.arr) {
yield t;
}
}
}
function smallestK(arr: number[], k: number): number[] {
const heap = new Heap((t1, t2) => t2 - t1);
arr.forEach(v => heap.add(v));
const ans: number[] = [];
while (k--) ans.push(heap.remove());
return ans;
}