给你一个整数 n ,请你找出并返回第 n 个 丑数 。

丑数 就是只包含质因数 2、3 和/或 5 的正整数。

示例 1:

输入:n = 10

输出:12

解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。

示例 2:

输入:n = 1

输出:1

解释:1 通常被视为丑数。


/**
* @param {number} n
* @return {number}
// */
// var nthUglyNumber = function(n) {
// // 1 为丑数
// const dp = [1, new Array(n - 1)]
// let p2 = 0;
// let p3 = 0;
// let p5 = 0;
// for (let i = 1; i < n; i++) {
// let num2 = dp[p2] * 2;
// let num3 = dp[p3] * 3;
// let num5 = dp[p5] * 5;
// dp[i] = Math.min(num2, num3, num5);
// if (dp[i] === num2){
// p2 ++
// }
// if (dp[i] === num3){
// p3 ++
// }
// if (dp[i] === num5){
// p5 ++
// }

// }
// console.log(dp);
// return dp[n-1]
// };


var nthUglyNumber = function(n) {
let seen = new Set();
let heap = new MinHeap();
let res = 0;
let arr = [2,3,5]
heap.insert(1);
seen.add(1)
for (let i = 0; i < n; i++) {
res = heap.pop()
for(let j = 0; j < arr.length; j++) {
let num = res * arr[j];
console.log(num)
if (!seen.has(num)) {
heap.insert(num);
seen.add(num)
}
}

}
return res
}


// 最小堆
class MinHeap {
constructor() {
this.heap = [];
}

getParentIndex(i) {
return (i - 1) >> 1;
}

getLeftIndex(i) {
return i * 2 + 1;
}

getRightIndex(i) {
return i * 2 + 2;
}

shiftUp(index) {
if(index === 0) { return; }
const parentIndex = this.getParentIndex(index);
if(this.heap[parentIndex] > this.heap[index]){
this.swap(parentIndex, index);
this.shiftUp(parentIndex);
}
}

swap(i1, i2) {
const temp = this.heap[i1];
this.heap[i1]= this.heap[i2];
this.heap[i2] = temp;
}

insert(value) {
this.heap.push(value);
this.shiftUp(this.heap.length - 1);
}

pop() {
this.heap[0] = this.heap.pop();
this.shiftDown(0);
return this.heap[0];
}

shiftDown(index) {
const leftIndex = this.getLeftIndex(index);
const rightIndex = this.getRightIndex(index);
if (this.heap[leftIndex] < this.heap[index]) {
this.swap(leftIndex, index);
this.shiftDown(leftIndex);
}
if (this.heap[rightIndex] < this.heap[index]){
this.swap(rightIndex, index);
this.shiftDown(rightIndex);
}
}

peek() {
return this.heap[0];
}

size() {
return this.heap.length;
}
}