heapq库,大顶堆,小顶堆的使用笔记

本文介绍了如何在在线Python编译器中使用heapq模块创建堆、最大堆以及获取前K个最大值和最小值。示例代码展示了heapify函数的应用和heappush、heappop等操作。
摘要由CSDN通过智能技术生成
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.


import heapq

#--------------------create new heap
nums = [2,5,1,6,9,0]

heap = []

for num in nums:
    heapq.heappush(heap,num)
    
print(heap)


print([heapq.heappop(heap) for _ in range(len(heap))])
#result:
#[0, 5, 1, 6, 9, 2]
#[0, 1, 2, 5, 6, 9]



#--------------------create new heap in place
nums = [2,5,1,6,9,0]
heapq.heapify(nums)
print([heapq.heappop(nums) for _ in range(len(nums))])
#result:
#[0, 1, 2, 5, 6, 9]



# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.


import heapq

#--------------------create Max heap
nums = [2,5,1,6,9,0]

heap = []

for num in nums:
    heapq.heappush(heap,-num)

print(heap)

print([-heapq.heappop(heap) for _ in range(len(heap))])

#result
#[-9, -6, -1, -2, -5, 0]
#[9, 6, 5, 2, 1, 0]



#--------------------create topK, minK
nums = [2,5,1,6,9,0]

heapq.heapify(nums)

print(heapq.nlargest(4, nums))

print(heapq.nsmallest(4, nums))

#result
#[9, 6, 5, 2]
#[0, 1, 2, 5]
  • 19
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值