二叉堆时间复杂度 php,二叉堆(Binary Heap)
二叉堆這個數據結構有點意思,自己做了個總結,內容結構如下:
二叉堆性質
二叉堆操作
應用
二叉堆性質:
堆(Heap)是一個可以被看成近似完全二叉樹的結構,具有完全二叉樹的特性:
缺少的葉子節點總是位于右子節點
n個節點的完全二叉樹高度:k=? log2n?(向上取整)
從1開始按層序編號,那么第i個節點有如下性質:
其左子節點索引是:2i
其又子節點索引是:2i+1
其父節點索引為 : i // 2
同時具有堆的特性:
堆頂元素就是最值,O(1)時間就能優先拿到
從根節點(堆頂)到堆中每一個節點都是一個有序序列。
存儲方式可以用線性的數組來實現,實現簡單易操作,不過要注意數組下標從0開始,這個位置預留占位,節點的索引從1開始編號。
2.png
binarytree.png
二叉堆操作:
BinaryHeap():創建一個空的二叉堆對象
insert(key):將新元素加入到堆中
findMin():返回堆中的最小項,最小項仍保留在堆中
delMin():返回堆中的最小項,同時從堆中刪除
isEmpty():返回堆是否為空
size():返回堆中節點的個數
buildHeap(lst):從一個包含節點的列表里創建新堆
# 直接導入Pythonds包使用其提供的有關堆的數據結構。
from pythonds.trees import BinaryHeap
bheap=BinaryHeap()
bheap.insert(5)
#用list來實現對堆的操作
class BinaryHeap(object):
"""定義一個二叉堆"""
def __init__(self):
self.heapList = [0] # 第一個堆元素從1開始編號,索引為0占位不用
self.currentSize = 0
def percolateUP(self, i):
'''將第i個元素上浮到合適位置'''
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
self.heapList[i], self.heapList[
i // 2] = self.heapList[i // 2], self.heapList[i]
else:
break
i = i // 2
def percolateDown(self, i):
'''將第i個元素下沉到合適位置'''
while (2 * i) <= self.currentSize:
minIndex = self.minChild(i)
if self.heapList[i] > self.heapList[minIndex]:
self.heapList[i], self.heapList[
minIndex] = self.heapList[minIndex], self.heapList[i]
else:
break
i = minIndex
def minChild(self, i):
'''返回第i個元素左右子節點中最小值'''
if (2 * i + 1) > self.currentSize:
return 2 * i # 只有一個子節點(左子節點)
elif self.heapList[2 * i] < self.heapList[2 * i + 1]:
return 2 * i
else:
return 2 * i + 1
def insert(self, key):
'''將新元素加入到堆中'''
self.heapList.append(key)
self.currentSize = self.currentSize + 1
self.percolateUP(self.currentSize) # 新值上浮
def findMin(self):
'''返回堆中的最小項,最小項仍保留在堆中'''
return heapList[1]
def delMin(self):
'''返回堆中的最小項,同時從堆中刪除'''
result = self.heapList[1]
# 將最后一個元素換到堆頂并刪除堆頂元素
self.heapList[1] = self.heapList.pop()
self.currentSize = self.currentSize - 1
self.percolateDown(1) # 將堆頂元素下沉
return result
def isEmpty(self):
'''返回堆是否為空'''
return len(heapList) == 1
def size(self):
'''返回堆中節點的個數'''
return len(heapList) - 1
def printHeap(self):
print(self.heapList[1:])
def buildHeap(self, lst):
'''從一個包含節點的列表里創建新堆,用下沉法將時間復雜度控制在O(n)'''
self.currentSize = len(lst)
i = self.currentSize // 2 #從最后一個節點的父節點開始過濾下沉!
self.heapList = [0] + lst[:]
while i > 0:
self.percolateDown(i)
i = i - 1
self.printHeap()
應用之一-----------------優先隊列:
可以在O(1)時間拿到最值,獲取最優解,實現對VIP或者進程的優先級等操作
pic_19.png
應用之二-----------------堆排序:
總結
以上是生活随笔為你收集整理的二叉堆时间复杂度 php,二叉堆(Binary Heap)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南开大学计算机原理在线作业,南开大学20
- 下一篇: 前端React结构工程-改写render