LC: 剑指 Offer 49. 丑数

题目:

剑指 Offer 49. 丑数。

我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。

链接:https://leetcode-cn.com/leetbook/read/illustrate-lcof/50qoxc/

本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/

示例

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

说明:
1 是丑数。
n 不超过1690。

思路:

除第一个丑数外,其余丑数皆为2或3或5的倍数。

每次取2,3,5倍数的最小值存入列表中,倍数通过已存入列表的值控制。

最后将第n个数丑数返回。

代码:

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        arr = [1]
        a, b, c = 0, 0, 0
        for i in range(1, n):
            times2, times3, times5= arr[a]*2, arr[b]*3, arr[c]*5
            arr.append(min(min(times2, times3), times5))
            if arr[-1] == times2:
                a += 1
            if arr[-1] == times3:
                b += 1
            if arr[-1] == times5:
                c += 1
        return arr[n-1]

时间复杂度O(n),空间复杂度O(n).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值