Ugly Number II

Problem: Ugly Number II

We mainly use the hints as our general idea, that is maintain 3 lists. For example:

times 2 times 3 times 5 min
1 1 1 2
2 1 1 3
2 2 1 4
3 2 1 5
3 2 2 6
4 3 2 8
5 3 2 9

From the example, we can acknowledge that actually we can only one list to maintain all sorted calculated ugly numbers and 3 numbers to point to different positions of the list. For other calculation please refer to the hint.

Code in Python:

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = [1]
        l1 = l2 = l3 = 0
        while len(res) < n:
            u1, u2, u3 = res[l1]*2, res[l2]*3, res[l3]*5
            u = min([u1, u2, u3])
            res.append(u)
            if u == u1:
                l1 += 1
            if u == u2:
                l2 += 1
            if u == u3:
                l3 += 1
        return res[-1]

results matching ""

    No results matching ""