https://leetcode.cn/problems/ugly-number-ii/submissions/595972540/
最小堆,这题没想出来,真妙
/**
* @param {number} n
* @Return {number}
*/
class Heap {
constructor(comparator = (a, b) => a - b) {
this.heap = [];
this.comparator = comparator;
}
getParentIndex(index) {
return Math.floor((index - 1) / 2);
}
getLeftChildIndex(index) {
return 2 * index + 1;
}
getRightChildIndex(index) {
return 2 * index + 2;
}
swap(index1, index2) {
const temp = this.heap[index1];
this.heap[index1] = this.heap[index2];
this.heap[index2] = temp;
}
insert(value) {
this.heap.push(value);
this.heapifyUp();
}
heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = this.getParentIndex(index);
if (this.comparator(this.heap[index], this.heap[parentIndex]) < 0) {
this.swap(index, parentIndex);
index = parentIndex;
} else {
break;
}
}
}
extractMin() {
if (this.heap.length === 0) {
return null;
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return min;
}
heapifyDown(index) {
let smallest = index;
const leftChildIndex = this.getLeftChildIndex(index);
const rightChildIndex = this.getRightChildIndex(index);
if (
leftChildIndex < this.heap.length &&
this.comparator(this.heap[leftChildIndex], this.heap[smallest]) < 0
) {
smallest = leftChildIndex;
}
if (
rightChildIndex < this.heap.length &&
this.comparator(this.heap[rightChildIndex], this.heap[smallest]) < 0
) {
smallest = rightChildIndex;
}
if (smallest !== index) {
this.swap(index, smallest);
this.heapifyDown(smallest);
}
}
peek() {
return this.heap.length > 0 ? this.heap[0] : null;
}
size() {
return this.heap.length;
}
}
var nthUglyNumber = function (n) {
const minHeap = new Heap((a, b) => a - b);
minHeap.insert(1);
const visit = new Set();
let ugly = 0;
let list = [2, 3, 5];
for (let index = 0; index < n; index++) {
ugly = minHeap.extractMin();
for (const num of list) {
const mul = num * ugly;
if (!visit.has(mul)) {
visit.add(mul);
minHeap.insert(mul);
}
}
}
return ugly;
};