LeetCode 剑指 Offer 49. 丑数
题目描述
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
剑指 Offer 49. 丑数
提示:
1 是丑数。
n 不超过1690。
一、解题关键词
二、解题报告
1.思路分析
1、存储因子然后计算
2、set存储计算结果 防止出现公共的数
2.时间复杂度
3.代码示例
class Solution {
public int nthUglyNumber(int n) {
if(n < 2){return 1;}
int [] factots = {2,3,5};
Set<Long> seen = new HashSet<>();
PriorityQueue<Long> heap = new PriorityQueue<>();
seen.add(1L);
heap.offer(1L);
int ugly = 0;
for(int i = 0; i < n; i++){
long curr = heap.poll();
ugly = (int)curr;
for(int factot : factots){
long next = curr * factot;
if(seen.add(next)){
heap.offer(next);
}
}
}
return ugly;
}
}
2.知识点
总结
也可以使用动态规划求解