友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
264. 丑数 II
给你一个整数 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 通常被视为丑数。
提示:
-
1 <= n <= 1690
思路分析
生成出来丑数队列,然后从中选出第 n
个数。
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-07-05 23:32:25
*/
public int nthUglyNumber(int n) {
int[] bases = new int[]{2, 3, 5};
Set<Long> nums = new HashSet<>();
Queue<Long> queue = new PriorityQueue<>();
nums.add(1L);
queue.add(1L);
for (int i = 1; i <= n; i++) {
long item = queue.poll();
if (i == n) {
return (int) item;
}
for (int base : bases) {
long next = base * item;
if (!nums.contains(next)) {
nums.add(next);
queue.add(next);
}
}
}
return -1;
}