丑数就是只包含质因数 2
、3
和/或 5
的正整数。1也是丑数。
丑数一定是比它小的丑数乘2、3、5得到的。
class Solution(object):
def nthUglyNumber(self, n):
res = [1] * n
a, b, c = 0, 0, 0
for i in range(1,n):
n2, n3, n5 = res[a] * 2, res[b] * 3, res[c] * 5
res[i] = min(n2, n3, n5)
if res[i] == n2: a += 1
if res[i] == n3: b += 1
if res[i] == n5: c += 1
return res[-1]
可以理解成从1开始维护一个丑数数组,a,b,c表示当前的丑数乘以2,3,5还没放入丑数数组(a指向的丑数只和2乘,b和3,c和5)
res 1,2,3,4,5,6,8,9,10 ...
计算过程
2*1,2*2,2*3,2*4,2*5,2*6,2*8,2*9 ...
3*1,3*2,3*3,3*4,3*5,3*6,3*8,3*9 ...
5*1,5*2,5*3,5*4,5*5,5*6,5*8,5*9 ...