leetcode: 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.

 

思路

这题的思路很有意思。

1、对于 乘积因子 2,3,5 记录他们该乘列表中的哪个数了。

2、三个因子 乘各自该乘的数,然后选择其中最小的,附在列表后面。

3、更新 因子该乘的数 (由于数字是从小到大排列的,所以因子该乘的数,为列表中该因子当前所乘数的下一个),用图来表示:

 

答案

    def nthUglyNumber(self, n: int) -> int:
        i2,i3,i5 = 0,0,0
        uglyNums = [1]
        n0 = 1
        while n0 < n:
            u2, u3, u5 = 2*uglyNums[i_f2], 3*uglyNums[i_f3], 5*uglyNums[i_f5]
            u_min = min([u2, u3, u5])
            
            # 这里可能出现成绩结果相同的情况,所以需要对每个factor更新,而不是只更新乘积的
            if u_min == u_multiply2:
                i_f2 += 1
            if u_min == u_multiply3:
                i_f3 += 1
            if u_min == u_multiply5:
                i_f5 += 1
            uglyNums.append(u_min)
            n0+=1
        return uglyNums[-1]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值