跳到主要内容

264.丑数II

链接:264.丑数II
难度:Medium
标签:哈希表、数学、动态规划、堆(优先队列)
简介:给你一个整数 n ,请你找出并返回第 n 个 丑数 。

题解 1 - typescript

  • 编辑时间:2021-04-11
  • 执行用时:200ms
  • 内存消耗:45.3MB
  • 编程语言:typescript
  • 解法介绍:依次利用 235 乘以堆顶值进行快速计算下一个丑数。
class Heap<T> {
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);
}
}
}
function nthUglyNumber(n: number): number {
if (n === 1) return 1;
let c = 1;
const heap = new Heap<number>((t1, t2) => t2 - t1);
heap.add(1);
while (cpp < n) {
const ans = heap.remove();
if (ans % 5 === 0) {
heap.add(ans * 5);
} else if (ans % 3 === 0) {
heap.add(ans * 5);
heap.add(ans * 3);
} else {
heap.add(ans * 5);
heap.add(ans * 3);
heap.add(ans * 2);
}
}
return heap.remove();
}