LeetCode----Ugly NumberII

本文介绍了一种高效算法来找到第N个丑数。丑数是指只包含质因数2、3和5的正整数。文章提供了两种实现方法,一种使用最小堆,另一种通过动态维护候选丑数列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Hint:

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


分析:

没看Hint之前,我以为可以用母函数来做,后来发现母函数之间的组合是加法,这里是乘法。之后又使用三层循环暴力组合2,3,5,结果一直超时。


代码1,使用最小堆:

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        from heapq import heappop, heappush
        h2, h3, h5 = [2], [3], [5]
        min_num = 1
        while n > 1:
            u2, u3, u5 = h2[0], h3[0], h5[0]
            min_num = min(u2, u3, u5)
            if min_num == u2:
                heappop(h2)
                heappush(h2, u2 * 2)
                heappush(h3, u2 * 3)
                heappush(h5, u2 * 5)
            if min_num == u3:
                heappop(h3)
                heappush(h3, u3 * 3)
                heappush(h5, u3 * 5)
            if min_num == u5:
                heappop(h5)
                heappush(h5, u5 * 5)
            n -= 1
        return min_num

使用了三个堆,使用堆会使时间消耗过大。


代码2:

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        uglylst = [1]
        i2, i3, i5 = 0, 0, 0  # represent the uglylst index
        while n > 1:
            u2, u3, u5 = uglylst[i2] * 2, uglylst[i3] * 3, uglylst[i5] * 5
            min_num = min(u2, u3, u5)
            if min_num == u2:
                i2 += 1
            if min_num == u3:
                i3 += 1
            if min_num == u5:
                i5 += 1
            uglylst.append(min_num)
            n -= 1
        return uglylst[-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值