4.數據結構---堆

1、堆

1.最小堆 【Python heapq模塊】

heap爲定義堆,item增長的元素 heapq.heappush(heap,item) python

>>> import heapq
>>> h = []
>>> heapq.heappush(h,2)
>>> h
[2]

將列表轉換爲堆 heapq.heapify(list) api

>>> list = [1,2,3,5,1,5,8,9,6]
>>> heapq.heapify(list)
>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]

刪除最小值,由於堆的特徵是heap[0]永遠是最小的元素,因此通常都是刪除第一個元素 heapq.heappop(heap) app

>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]
>>> heapq.heappop(list)
1
>>> list
[1, 2, 3, 5, 6, 5, 8, 9]

刪除最小元素值,添加新的元素值 heapq.heapreplace(heap.item) spa

>>> list
[1, 2, 3, 5, 6, 5, 8, 9]
>>> heapq.heapreplace(list,99)
1
>>> list
[2, 5, 3, 9, 6, 5, 8, 99] 

首先判斷添加元素值與堆的第一個元素值對比,若是大,則刪除第一個元素,而後添加新的元素值,不然不更改堆 heapq.heapreplace(heap,item).net

>>> list
[2, 5, 3, 9, 6, 5, 8, 99]
>>> heapq.heappushpop(list,6)
2
>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.heappushpop(list,1)
1
>>> list
[3, 5, 5, 9, 6, 6, 8, 99] 

將多個堆合併 heapq.merge(…) blog

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> h
[1000]
>>> for i in heapq.merge(h,list):
...     print(i,end=" ")
...
3 5 5 9 6 6 8 99 1000 

查詢堆中的最大元素,n表示查詢元素個數  heapq.nlargest(n,heap)get

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nlargest(3,list)
[99, 9, 8]
>>>

查詢堆中的最小元素,n表示查詢元素的個數 heapq.nsmallest(n,heap) it

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nsmallest(3,list)
[3, 5, 5]

2.最大堆

用heapy創建大頂堆:將數據以相反數的形式存入堆,再以相反數的形式取出入門

push(e)  --->>> push(-e)
pop(e) --->>> pop(-e)

 

  

參考文獻:class

【1】python3入門之堆(heapq)

相關文章
相關標籤/搜索