mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 264. Ugly Number II.md
This commit is contained in:
parent
b07b73d2c2
commit
b187e57d05
32
solutions/264. Ugly Number II.md
Normal file
32
solutions/264. Ugly Number II.md
Normal file
@ -0,0 +1,32 @@
|
||||
# 思路
|
||||
要求第n个ugly数. 由于ugly集合相对于整个int集合是很小的, 所以此题用蛮力法不断判断某个数是否ugly肯定会超时. 所以我们应该从直接构造ugly数着手.
|
||||
|
||||
那么如何直接构造ugly数呢? 根据ugly数的定义可知, 如果x, y, z都是ugly的, 那么2x, 3y, 5z都是ugly数, 所以我们可以从初始x=y=z=1开始不断构造ugly数.
|
||||
|
||||
题目要求第n大的ugly数, 所以可以维护一个从小到大的ugly数组, 每次取2x, 3y, 5z三者最小的push进数组作为下一个ugly数, 详情可见代码.
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
int nthUglyNumber(int n) {
|
||||
vector<int>ugly{1};
|
||||
|
||||
int idx2 = 0, idx3 = 0, idx5 = 0;
|
||||
int tmp2, tmp3, tmp5;
|
||||
while(1){
|
||||
if(!(--n)) break;
|
||||
tmp2 = ugly[idx2] * 2;
|
||||
tmp3 = ugly[idx3] * 3;
|
||||
tmp5 = ugly[idx5] * 5;
|
||||
|
||||
int next = min(tmp2, min(tmp3, tmp5));
|
||||
if(next == tmp2) idx2++;
|
||||
if(next == tmp3) idx3++;
|
||||
if(next == tmp5) idx5++;
|
||||
ugly.push_back(next);
|
||||
}
|
||||
return ugly.back();
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user