天天看點

python子產品之heapq子產品(堆)基本操作heapq 子產品基本操作

heapq 子產品基本操作

1、導入子產品:

2、heapq 提供的常用方法

heapq.heapify(head)   *# 将數組轉化成堆*
heapq.heappop(head)   # *删除堆頂,也就是最小值*
heapq.heappush(head,item)     # *往堆中增元素*
heapq.nlargest(N,head)     # *查堆中最大的N個數*
heapq.nsmallest(N,head)    # *查堆中最小的N個數*
           

2.1、将數組轉化成堆

head = [3,2,1,4,5]
heapd.heapify(head)
           

2.2、删除堆頂

2.3、在堆中增加元素

2.4、查堆中最大的N個數

2.5、查詢堆中最小的N個數