################堆 heap
class maxheap: #索引0不用,所以陣列大小應該是 n+1
##左節點2i 右節點2i+1,父節點 i/2
def __init__(self):
self._data= #堆陣列容量不知道
self._count=len(self._data)
def size(self):
return self._count
def isempty(self):
return self._count==0
def add(self,item):##新增
assert self._count+1<=capacity,"超出陣列容量"##可加可不加
self._count+=1
self._shiftup(self._count)#上移,傳遞最後乙個索引
def _shiftup(self,index):##索引要考慮索引越界,所以邊界什麼情況
# 新增元素,然後上移元素,滿足不大於父元素的特性
parent=(index)/2 #父節點索引大於等於1,所以index 最小2
while (index>1 and self._data[parent])0
ret = self._data[0]
self._data[0]=self._data[self._count]#最後乙個值填充到第乙個位置
self._count=self._count-1
self._shiftdown(1) #下移傳遞第乙個索引
return ret
def _shiftdown(self,index):#先判斷是否有子節點,完全二叉樹,不可能右節點,沒有左節點
while (2*index<=self._count): #迴圈判斷當前節點的左節點是否存在,如果不存在已經比較結束了
#先找到左右子樹的最大值是哪個
j = 2*index
if j+1 <=self._count and self._data[j+1]>self._data[j]:
j=j+1
if self._data[index]>=self._data[j]
break
#交換,如果分行寫需要中間變數,這樣寫可以直接交換
self._data[index], self._data[j] = self._data[j], self._data[index]
self._data[index]
index=j #索引跟隨值移動,往下
python實現最大堆
堆是利用的完全二叉樹的性質,並且利用陣列來實現的一種特殊資料結構 class myheap object max heap def init self self.heap def add self,item self.heapity len self.heap 1 def show self pri...
C 最大堆實現
max heap.h pragma once include template class max heap node heap 最大堆 uint32 t max size 最大儲存數 uint32 t size 儲存數 擴容 void expansion 刪除指定下標節點 void del nod...
LeetCode 實現最大堆
優先佇列 priority queue 可以在o 1 時間內獲取最大值,並且在0 logn 時間內取出最大值或插入任意值.優先佇列常常用堆 heap 來實現,堆是乙個完全二叉樹,其每個節點的值總是大於等於或小於等於子節點的值.實際 實現堆時,通常用乙個陣列而不是指標建立一盒樹.這是因為堆是完全二叉樹...