mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update 264
This commit is contained in:
parent
a8335f982c
commit
cbdaa6448d
@ -6,6 +6,8 @@
|
|||||||
|
|
||||||
题目要求第n大的ugly数, 所以可以维护一个从小到大的ugly数组, 每次取2x, 3y, 5z三者最小的push进数组作为下一个ugly数, 详情可见代码.
|
题目要求第n大的ugly数, 所以可以维护一个从小到大的ugly数组, 每次取2x, 3y, 5z三者最小的push进数组作为下一个ugly数, 详情可见代码.
|
||||||
|
|
||||||
|
时空复杂度均为O(n)
|
||||||
|
|
||||||
# C++
|
# C++
|
||||||
``` C++
|
``` C++
|
||||||
class Solution {
|
class Solution {
|
||||||
@ -14,18 +16,14 @@ public:
|
|||||||
vector<int>ugly{1};
|
vector<int>ugly{1};
|
||||||
|
|
||||||
int idx2 = 0, idx3 = 0, idx5 = 0;
|
int idx2 = 0, idx3 = 0, idx5 = 0;
|
||||||
int tmp2, tmp3, tmp5;
|
int tmp2 = 2, tmp3 = 3, tmp5 = 5, next;
|
||||||
while(1){
|
while(--n){
|
||||||
if(!(--n)) break;
|
next = min(tmp2, min(tmp3, tmp5));
|
||||||
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);
|
ugly.push_back(next);
|
||||||
|
|
||||||
|
if(next == tmp2) tmp2 = ugly[++idx2] * 2;
|
||||||
|
if(next == tmp3) tmp3 = ugly[++idx3] * 3;
|
||||||
|
if(next == tmp5) tmp5 = ugly[++idx5] * 5;
|
||||||
}
|
}
|
||||||
return ugly.back();
|
return ugly.back();
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user