【Python】堆(heap)的基本操作

  • Post author:
  • Post category:python


#Python-堆(heap)的基本操作

import heapq #载入heap库,heap指的是最小堆


使数组转化为堆

heapq.heapify(list)

heap = [1,3,4,2,6,8,9]
heapq.heapify(heap)
# heap = [1,2,4,3,6,8,9]


为heap增加元素

heapq.heappush(heap,item)

  heap = [1,3,4,2,6,8,9]
  heapq.heappush(heap, 2)
  # heap = [1,3,4,2,6,8,9,2]


删除堆顶(即最小值)

heapq.heappop(heap)

  heap = [1,3,4,2,6,8,9]
  heapq.heappop(heap) 
  # heap = [3,2,4,9,6,8] #删除堆顶后将堆尾放到堆顶,然后下沉


删除最小值并添加新值

heapq.heapreplace(heap, item)

  heap = [1,3,4,2,6,8,9]
  heapq.heapreplace(heap, 4)
  # heap = [3,2,4,4,6,8,9]#删除堆顶后将新元素放到堆顶,然后下沉


查堆中最大n个数

heapq.nlargest (n, heap)

  heap = [1,3,4,2,6,8,9]
  result = heapq.nlargest (2, heap)
  # result = [9,8]


查堆中最小n个数

heapq.nsmallest(n, heap) #查询堆中的最小元素,n表示查询元素个数

 heap = [1,3,4,2,6,8,9]
 result = heapq.nsmallest (2, heap)
 # result = [1,2]



参考链接


https://blog.csdn.net/this_is_me_anyway/article/details/79755118



版权声明:本文为a529975125原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。