堆的常用操作

创建最小堆

这里的import heaqp只能用来创建最小堆;创建最大堆可以把列表中的元素提取出来乘负1,然后再加入列表中进行堆化操作,这样提取出来的堆顶也就是列表中最大的元素
最小堆的特性:二叉堆本质是一个二叉树,最小堆的堆顶是整个堆中最小的元素,同理,最大堆的堆顶就是整个堆中最大的元素。

把列表堆化成堆

heapq.heapify(list)

添加元素

heapq.heappush(minheap,10)

删除元素

heapq.heappop(minheap)

遍历堆顶元素

        while len(minheap)!=0:
            print(heapq.heappop(minheap)) #100 110 1110

完整代码

import heapq

class Test:
    def test(self):
        # create minheap;创建最小堆
        # minheap=[]
        minheap=[]
        heapq.heapify(minheap) # 把列表堆化成堆
        heapq.heappush(minheap,10)
        heapq.heappush(minheap,100)
        heapq.heappush(minheap,1)
        heapq.heappush(minheap,110)
        heapq.heappush(minheap,1110)
        print(minheap) # [1, 100, 10, 110, 1110]
        #peak
        print(minheap[0]) # 1
        # delete删除堆顶
        heapq.heappop(minheap) # 10
        # size
        len(minheap) 
        # 遍历堆顶元素
        while len(minheap)!=0:
            print(heapq.heappop(minheap)) #100 110 1110

a = Test()
a.test()
# [99999]*-1为空列表
# a.test([99999]*-1) 

posted @ 2021-09-25 20:11  索匣  阅读(69)  评论(0编辑  收藏  举报