暴力解法,就是一直往下算,挨个判断是不是丑数,这种方式也就是能用在1000以内不会超时,达到题目要求的1690肯定超时;
换个思想就是按照顺序求出每一个丑数;这里我们要保证求出丑数一定是按照从小到大排序;
class Solution {
public:
int nthUglyNumber(int n) {
if (n==1)
return 1;
vector<int>uglys(n);
uglys[0]=1;
int x=0,y=0,z=0,index=1;
while (index<n){
int tmp=min(min(uglys[x]*2,uglys[y]*3),uglys[z]*5);
uglys[index]=tmp;
//确保uglys[x]*2,uglys[y]*3),uglys[z]*5中的值一定大于uglys[index]
if(2*uglys[x]==uglys[index])x++;
if(3*uglys[y]==uglys[index])y++;
if(5*uglys[z]==uglys[index])z++;
index++;
}
return *(uglys.end()-1);
}
};
class Solution:
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n is 1:
return 1
uglys=[None]*n
uglys[0]=1
x=y=z=0
index=1
while index<n:
tmp=min(uglys[x]*2,uglys[y]*3,uglys[z]*5)
uglys[index]=tmp
if uglys[x]*2 == uglys[index]:
x+=1
if uglys[y]*3 == uglys[index]:
y+=1
if uglys[z]*5 == uglys[index]:
z+=1
index+=1
return uglys[n-1]