LeetCode 264.丑数

LeetCode 264.丑数

在做这个题目之前我们先自己造个轮子——实现一个堆

维护堆的性质

def max_heapify(A,i):
    left = 2*i+1
    right = 2*i+2
    max = i
    if left < len(A) and A[left]> A[i]:
        max = left
    if right < len(A) and A[right] > A[max]:
        max = right
    if max != i:
        A[i], A[max] = A[max], A[i]
        A = max_heapify(A, max)
    return A

A = [16,4,10,14,7,9,3,2,8,1]
print(max_heapify(A,1))
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]

堆的建立

def build_heap(A):
    heap_size = len(A)
    for i in range(heap_size//2,-1,-1):
        A = max_heapify(A, i)
    return A
build_heap([1,4,2,3,7,9,8,16,14,10])
[16, 14, 9, 4, 10, 2, 8, 3, 1, 7]

堆排序

def heap_sort(A):
    B = []
    A = build_heap(A)
    for i in range(len(A)-1,0,-1):
        A[i], A[0] = A[0], A[i]
        B.append(A.pop(-1))
        max_heapify(A, 1)
    return B
heap_sort([6,7,2,5,4,2,3])
[7, 2, 2, 4, 5, 3]

LeetCode 264.丑数

动态规划求解

def nthUglyNumber(n) -> int:
    dp = [1]
    i2, i3, i5 = 0, 0, 0
    while n > 1:
        dp.append(min(2*dp[i2], 3*dp[i3], 5*dp[i5]))
        if dp[-1]>= dp[i2]*2 : i2 += 1
        if dp[-1]>= dp[i3]*3 : i3 += 1
        if dp[-1]>= dp[i5]*5 : i5 += 1
        n = n - 1
    return dp[-1]        

优先队列求解

import heapq
def nthUglyNumber(n) -> int:
    heap = [1]
    heapq.heapify(heap)
    while n > 0:
        res = heapq.heappop(heap)
        while heap and res == heap[0]:
            res = heapq.heappop(heap)
        for i in [2,3,5]:
            heapq.heappush(heap,i*res)
        n = n - 1

    return res

欢迎关注公众号 : 数学算法实验室

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值