264. Ugly Number II -Medium

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, and n does not exceed 1690.

找到第n个丑数。丑数是有限个2、3、5的乘积,例如1,2,3,4,5,6,8,9,10,12是前10个丑数(1是特殊的丑数)。n不大于1690

Example

  • 见题目

Solution

  • 动态规划解。我刚开始考虑的是dp[i]代表i是否为丑数,它的确定只需要知道dp[i % 2], dp[i % 3]和dp[i % 5],只要有一个是丑数,那么dp[i]必然也是丑数,然后统计丑数的个数直到n。可是这样我没法确定到底dp需要多大,所以需要换个思路。dp[i]应该代表第i个丑数,那么它的递推关系该怎么找呢?其实很简单,因为下一个丑数必然是乘以2,3或5中的最小的那个数,所以我们只需分别记下乘以2,乘以3,乘以5的最小的数的索引,那么 dp[i] = min(dp[index_2] * 2, dp[index_3] * 3, dp[index_5] * 5),每次得到dp[i]不要忘了更新索引就可以了(注意:因为有可能dp[index_2] * 2和dp[index_3] * 3是相等的,这种情况,两个索引都要更新)

    class Solution(object):
        def nthUglyNumber(self, n):
            """
            :type n: int
            :rtype: int
            """
            dp = [0] * n
            # 1为第一个丑数
            dp[0] = 1
            # 从1开始向前寻找
            index_2, index_3, index_5 = 0, 0, 0
            for i in range(1, n):
                dp[i] = min(dp[index_2] * 2, dp[index_3] * 3, dp[index_5] * 5)
                # 这里不要elif,因为两个值可能相等,索引都需要更新
                if dp[i] == dp[index_2] * 2: index_2 += 1
                if dp[i] == dp[index_3] * 3: index_3 += 1
                if dp[i] == dp[index_5] * 5: index_5 += 1
            return dp[n - 1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值