Leetcode: Ugly Number II

来源:互联网 发布:人工智能的龙头股票 编辑:程序博客网 时间:2024/05/16 09:12

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 = [0]*n        res[0] = 1        index2, index3, index5 = 0, 0, 0        for ind in range(1,n):            res[ind] = min( [res[index2]*2, res[index3]*3, res[index5]*5] )            if res[ind]==res[index2]*2:                index2 += 1            if res[ind]==res[index3]*3:                index3 += 1            if res[ind]==res[index5]*5:                index5 += 1        return res[-1]
0 0
原创粉丝点击