首页 > 其他 > 详细

leetcode-264-丑数

时间:2019-10-11 10:28:59      阅读:65      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 方法一:堆 O(nlogn)

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        import heapq
        heap = [1]
        res = 0
        heapq.heapify(heap)
        for _ in range(n):
            res = heapq.heappop(heap)
            while heap and res == heap[0]:
                res = heapq.heappop(heap)
            a,b,c = res*2,res*3,res*5
            for t in [a,b,c]:
                heapq.heappush(heap,t)
        return res

方法二:动态规划 O(N)

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp = [0] * n
        dp[0] = 1
        l2,l3,l5 = 0,0,0
        for i in range(1,n):
            dp[i] = min(dp[l2]*2,dp[l3]*3,dp[l5]*5)
            if dp[i]>=dp[l2]*2:
                l2 += 1
            if dp[i]>=dp[l3]*3:
                l3 += 1
            if dp[i]>=dp[l5]*5:
                l5 += 1
        return dp[-1]

 

leetcode-264-丑数

原文:https://www.cnblogs.com/oldby/p/11652128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!