每日leetcode4.10(丑数I、II)

每日leetcode4.10(丑数)

263.丑数(简单)

一直除
class Solution:
    def isUgly(self, n: int) -> bool:
        if n == 0:
            return False
        nums = [2, 3, 5]
        for i in nums:
            while n % i == 0:
                n /= i
        return n == 1

264. 丑数 II

解法一:py中的堆结构
import heapq

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        h = [1]
        mp = [1]
        nums = [2, 3, 5]
        for i in range(n - 1):
            x = heapq.heappop(h)
            for j in nums:
                t = j * x
                if t not in mp:
                    heapq.heappush(h, t)
                    mp.append(t)
        return heapq.heappop(h)


if __name__ == '__main__':
    x = Solution()
    print(x.nthUglyNumber(10))

解法二:动态规划+三指针
class Solution:
    def nthUglyNumber(self, n: int) -> int:
        nums = [2, 3, 5]
        dp = [1]
        ptr = [0, 0, 0]
        l = 0
        while l < n:
            minX = min(dp[ptr[0]] * 2, dp[ptr[1]] * 3, dp[ptr[2]] * 5)
            dp.append(minX)
            l += 1
            for i in range(3):
                if minX == dp[ptr[i]] * nums[i]:
                    ptr[i] += 1
        return dp.pop()


if __name__ == '__main__':
    x = Solution()
    for i in range(10):
        print(x.nthUglyNumber(i))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值