264. Ugly Number II

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

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.

 

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        nums = [1]
        i = 0
        j = 0
        k = 0
        
        for _ in range(n-1):
            ugly = min(nums[i]*2, nums[j]*3, nums[k]*5)
            nums.append(ugly)
            
            if ugly == nums[i]*2:
                i += 1
            if ugly == nums[j]*3:
                j += 1
            if ugly == nums[k]*5:
                k += 1
        
        return nums[n-1]
            
            

 

posted @ 2020-03-21 19:35  米开朗菠萝  阅读(114)  评论(0)    收藏  举报