天天看點

Leetcode: Ugly Number IIQuestionSolution

Question

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

Show Hint

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Show Tags

Show Similar Problems

Solution

time complexity: O(n)

space complexity: O(n)

Get idea from here1, here2

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """

        res = []*n
        res[] = 
        index2, index3, index5 = , , 

        for ind in range(,n):
            res[ind] = min( [res[index2]*, res[index3]*, res[index5]*] )
            if res[ind]==res[index2]*:
                index2 += 
            if res[ind]==res[index3]*:
                index3 += 
            if res[ind]==res[index5]*:
                index5 += 

        return res[-]