1. 程式人生 > >python內建資料結構heapq【以後補充&修正】

python內建資料結構heapq【以後補充&修正】

heapq 最小堆

heapq.heapify()將列表原地轉換為堆。

sort()區別在於heap採用的是堆排序演算法,sort採用的是歸併排序演算法。

堆(heap)是一個樹形資料結構,其中子節點與父節點是一種有序關係。

二叉堆(Binary heap)可以使用以如下方式組織的列表或陣列表示,即元素N的子元素位於2*N+1和2*N+2(索引從0開始)。這種佈局允許原地重新組織堆,從而不必在增加或刪除元素時分配大量記憶體。

堆的邏輯結構就是完全二叉樹,並且二叉樹中父節點的值小於等於該節點的所有子節點的值。這種實現可以使用 heap[k] <= heap[2k+1] 並且 heap[k] <= heap[2k+2] (其中 k 為索引,從 0 開始計數)的形式體現,對於堆來說,最小元素即為根元素 heap[0]。

. heapq.py中提供的函式方法

heapq.heappush(heap, item) heapq.heappop(heap):返回 root 節點,即 heap 中最小的元素。 heapq.heapreplace(heap,item): python3中heappushpop的更高效版。 heapq.heappushpop(heap, item):向 heap 中加入 item 元素,並返回 heap 中最小元素。 heapq.heapify(x):Transform list into a heap, in-place, in O(len(x)) time heapq.merge(*iterables, key=None, reverse=False) heapq.nlargest(n, iterable, key=None):返回可列舉物件中的 n 個最大值,並返回一個結果集 list,key 為對該結果集的操作。 heapq.nsmallest(n, iterable, key=None):同上相反 heapq._heappop_max(heap): Maxheap version of a heappop  heapq._heapreplace_max(heap,item):Maxheap version of a heappop followed by a heappush. heapq._heapify_max(x):Transform list into a maxheap, in-place, in O(len(x)) time heapq._siftdown(heap,startpos,pos): Follow the path to the root, moving parents down until finding a place heapq._siftup(heap,pos):Bubble up the smaller child until hitting a leaf heapq._siftdown_max(heap,startpos,pos):Maxheap variant of _siftdown heapq._siftup_max(heap,pos):Maxheap variant of _siftup