lc264.丑数II

 

题目链接

此题与jz049.丑数相同。这个算法的时间复杂度是O(N),空间复杂度是O(N)。

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        res, a, b, c = [1]*n, 0, 0, 0
        for i in range(1, n):
            m2, m3, m5 = res[a] * 2, res[b] * 3, res[c]* 5
            res[i] = min(m2, m3, m5)
            if m2 == res[i]: a += 1
            if m3 == res[i]: b += 1
            if m5 == res[i]: c += 1
        return res[-1]