方法一,类似筛法素数,只能通过84%的数据。
const int maxn = 10000001;
bool num[maxn];
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if(index <= 0) return 0;
memset(num,0,sizeof(num));
num[1] = true;
int cnt = 0;
for(int i=0;i<maxn;i++){
if(num[i]){
cnt ++;
if(cnt == index) return i;
num[min(i*2,maxn)] = true;
num[min(i*3,maxn)] = true;
num[min(i*5,maxn)] = true;
}
}
return 0;
}
};
方法二,找M2, M3, M5:
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if(index <= 0) return 0;
vector<int> ans;
ans.push_back(1);
int loc2 = 0;
int loc3 = 0;
int loc5 = 0;
for(int i=2;i<=index;i++){
ans.push_back(min(ans[loc5]*5,min(ans[loc3]*3,ans[loc2]*2)));
while(ans[loc2]*2 <= ans[i-1]) loc2++;
while(ans[loc3]*3 <= ans[i-1]) loc3++;
while(ans[loc5]*5 <= ans[i-1]) loc5++;
}
return ans[ans.size()-1];
}
};