update 264

This commit is contained in:
ShusenTang 2020-02-11 18:25:03 +08:00
parent a8335f982c
commit cbdaa6448d

View File

@ -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();
} }