Skip to content

Commit 1b2c18e

Browse files
Update 264. 丑数 II.md
1 parent d1af9b7 commit 1b2c18e

File tree

2 files changed

+111
-1
lines changed

2 files changed

+111
-1
lines changed

Dynamic Programming/264. 丑数 II.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#### 264. 丑数 II
2+
3+
难度:中等
4+
5+
---
6+
7+
给你一个整数 `n` ,请你找出并返回第 `n`**丑数**
8+
9+
**丑数** 就是只包含质因数 `2``3` 和/或 `5` 的正整数。
10+
11+
**示例 1:**
12+
13+
```
14+
输入:n = 10
15+
输出:12
16+
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
17+
```
18+
19+
**示例 2:**
20+
21+
```
22+
输入:n = 1
23+
输出:1
24+
解释:1 通常被视为丑数。
25+
```
26+
27+
**提示:**
28+
29+
* `1 <= n <= 1690`
30+
31+
---
32+
33+
最小堆:
34+
35+
已知后面的丑数肯定是前面的丑数乘以2/3/5得到的。那么构造一个存放丑数的最小堆,每次弹出最小值,并且放入该值与2/3/5相乘的结果,并需要**去重**
36+
37+
```java
38+
class Solution {
39+
    public int nthUglyNumber(int n) {
40+
        PriorityQueue<Long> pq = new PriorityQueue<>();
41+
        pq.offer(1l);
42+
        long ans = 1l;
43+
        while(n-- != 0){
44+
            ans = pq.poll();
45+
            if(!pq.contains(ans * 2l)) pq.offer(ans * 2l);
46+
            if(!pq.contains(ans * 3l)) pq.offer(ans * 3l);
47+
            if(!pq.contains(ans * 5l)) pq.offer(ans * 5l);
48+
        }
49+
        return (int)ans;
50+
    }
51+
}
52+
```
53+
54+
55+
56+
动态规划:
57+
58+
定义三个指针 *p*2, *p*3, *p*5,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。
59+
60+
```go
61+
func nthUglyNumber(n int) int {
62+
dp := make([]int, n + 1)
63+
dp[1] = 1
64+
x2, x3, x5 := 1, 1, 1
65+
for i := 2; i <= n; i++ {
66+
s2, s3, s5 := dp[x2] * 2, dp[x3] * 3, dp[x5] * 5
67+
dp[i] = min(min(s2, s3), s5)
68+
if dp[i] == s2 {
69+
x2++
70+
}
71+
if dp[i] == s3 { // 不能用 else if,而是用 if。因为会有重复计算
72+
x3++
73+
}
74+
if dp[i] == s5 {
75+
x5++
76+
}
77+
}
78+
return dp[n]
79+
}
80+
```
81+

Priority Queue/264. 丑数 II.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,33 @@ class Solution {
4949
        return (int)ans;
5050
    }
5151
}
52-
```
52+
```
53+
54+
55+
56+
动态规划:
57+
58+
定义三个指针 *p*2, *p*3, *p*5,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。
59+
60+
```go
61+
func nthUglyNumber(n int) int {
62+
dp := make([]int, n + 1)
63+
dp[1] = 1
64+
x2, x3, x5 := 1, 1, 1
65+
for i := 2; i <= n; i++ {
66+
s2, s3, s5 := dp[x2] * 2, dp[x3] * 3, dp[x5] * 5
67+
dp[i] = min(min(s2, s3), s5)
68+
if dp[i] == s2 {
69+
x2++
70+
}
71+
if dp[i] == s3 { // 不能用 else if,而是用 if。因为会有重复计算
72+
x3++
73+
}
74+
if dp[i] == s5 {
75+
x5++
76+
}
77+
}
78+
return dp[n]
79+
}
80+
```
81+

0 commit comments

Comments
 (0)