环球观焦点:python实现堆(最大堆、最小堆、最小最大堆)

来源:腾讯云 时间:2023-04-01 07:24:59


(资料图片)

1. 最大堆

class MaxHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_max(self):        if not self.heap:            return None        return self.heap[0]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_max(self):        if not self.heap:            return None        max_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down(0)        return max_item    def _heapify_up(self, i):        while i > 0 and self.heap[i] > self.heap[self.parent(i)]:            self.heap[i], self.heap[self.parent(i)] = self.heap[self.parent(i)], self.heap[i]            i = self.parent(i)    def _heapify_down(self, i):        max_index = i        left = self.left_child(i)        if left < len(self.heap) and self.heap[left] > self.heap[max_index]:            max_index = left        right = self.right_child(i)        if right < len(self.heap) and self.heap[right] > self.heap[max_index]:            max_index = right        if i != max_index:            self.heap[i], self.heap[max_index] = self.heap[max_index], self.heap[i]            self._heapify_down(max_index)if __name__ == "__main__":    max_heap = MaxHeap()    max_heap.insert(1)    max_heap.insert(2)    max_heap.insert(0)    max_heap.insert(8)    print(max_heap.get_max())

2. 最小堆

class MinHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_min(self):        if not self.heap:            return None        return self.heap[0]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_min(self):        if not self.heap:            return None        min_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down(0)        return min_item    def _heapify_up(self, i):        while i > 0 and self.heap[i] < self.heap[self.parent(i)]:            self.heap[i], self.heap[self.parent(i)] = self.heap[self.parent(i)], self.heap[i]            i = self.parent(i)    def _heapify_down(self, i):        min_index = i        left = self.left_child(i)        if left < len(self.heap) and self.heap[left] < self.heap[min_index]:            min_index = left        right = self.right_child(i)        if right < len(self.heap) and self.heap[right] < self.heap[min_index]:            min_index = right        if i != min_index:            self.heap[i], self.heap[min_index] = self.heap[min_index], self.heap[i]            self._heapify_down(min_index)

3. 最小-最大堆

最小-最大堆的性质是:树中偶数层的每个节点都小于它的所有后代,而树中奇数层的每个节点都大于它的所有后代。

用途 双端优先级队列

class MinMaxHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_min(self):        if not self.heap:            return None        return self.heap[0]    def get_max(self):        if not self.heap:            return None        if len(self.heap) == 1:            return self.heap[0]        if len(self.heap) == 2:            return self.heap[1] if self.heap[1] > self.heap[0] else self.heap[0]        return self.heap[1] if self.heap[1] > self.heap[2] else self.heap[2]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_min(self):        if not self.heap:            return None        min_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down_min(0)        return min_item    def extract_max(self):        if not self.heap:            return None        max_item = self.get_max()        max_index = self.heap.index(max_item)        self.heap[max_index] = self.heap[-1]        self.heap.pop()        if max_index < len(self.heap):            self._heapify_down_max(max_index)        return max_item    def _heapify_up(self, i):        if i == 0:            return        parent = self.parent(i)        if self.heap[i] < self.heap[parent]:            self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]            self._heapify_up_max(parent)        else:            self._heapify_up_min(i)    def _heapify_up_min(self, i):        grandparent = self.parent(self.parent(i))        if i > 2 and self.heap[i] < self.heap[grandparent]:            self.heap[i], self.heap[grandparent] = self.heap[grandparent], self.heap[i]            self._heapify_up_min(grandparent)    def _heapify_up_max(self, i):        grandparent = self.parent(self.parent(i))        if i > 2 and self.heap[i] > self.heap[grandparent]:            self.heap[i], self.heap[grandparent] = self.heap[grandparent], self.heap[i]            self._heapify_up_max(grandparent)    def _heapify_down_min(self, i):        while True:            min_index = i            left = self.left_child(i)            if left < len(self.heap) and self.heap[left] < self.heap[min_index]:                min_index = left            right = self.right_child(i)            if right < len(self.heap) and self.heap[right] < self.heap[min_index]:                min_index = right            if i != min_index:                self.heap[i], self.heap[min_index] = self.heap[min_index], self.heap[i]                i = min_index            else:                break    def _heapify_down_max(self, i):        while True:            max_index = i            left = self.left_child(i)            if left < len(self.heap) and self.heap[left] > self.heap[max_index]:                max_index = left            right = self.right_child(i)            if right < len(self.heap) and self.heap[right] > self.heap[max_index]:                max_index = right            if i != max_index:                self.heap[i], self.heap[max_index] = self.heap[max_index], self.heap[i]                i = max_index            else:                break

在这个实现中,MinMaxHeap类代表一个min-max堆,包含一个list堆,用于存放堆中的元素。 parent、left_child 和right_child 方法分别返回节点的父节点、左子节点和右子节点的索引。 get_min 方法返回堆中的最小元素,get_max 方法返回堆中的最大元素。 insert 方法将一个元素插入到堆中并维护堆属性。 extract_min 方法从堆中移除最小元素并保持堆属性。 extract_max 方法从堆中移除最大元素并保持堆属性。

_heapify_up、_heapify_up_min、_heapify_up_max、_heapify_down_min 和 _heapify_down_max 方法用于维护最小-最大堆属性。 _heapify_up 在向堆中插入元素后调用,以确保元素位于正确的位置。 _heapify_up_min 和 _heapify_up_max 由 _heapify_up 调用以维护最小-最大堆属性。 _heapify_down_min 和 _heapify_down_max 分别被 extract_min 和 extract_max 调用,以维护 min-max 堆属性。

X 关闭

环球观焦点:python实现堆(最大堆、最小堆、最小最大堆)

最小-最大堆的性质是:树中偶数层的每个节点都小于它的所有后代,而树中奇数层的每个节点都大于它的所有后代。

2023-04-01

旭辉永升服务:管理层已对相关交易进行审查 确认合规并符合商业条款_世界热讯

公司管理层认为交易已在集团的管理账目中适当记录,且这些交易的进行具有充分的商业事实及业务理据,并按正常商业条款进行。

2023-04-01

小米米家智能窗帘正式开售 语音控制 窗帘开合随心控

6月10日,米家智能窗帘在小米商城开启众筹,众筹价699元。最终超2 3万人参与众筹,总金额超648万元。

2023-04-01

今日精选:巢马城际铁路全线首跨公路梁浇筑完成

(张俊刘洋森)3月30日,安徽省首条省市共建城际铁路——巢(巢湖市)马(马鞍山市)城际铁路建设取得突破性进展,全线首跨公路梁浇筑顺利完成。引桥

2023-03-31

雅高控股(03313)公布2022年业绩 拥有人应占亏损约1.48亿元 同比收窄64.52% 世界动态

智通财经APP讯,雅高控股(03313)公布2022年业绩,收益约为人民币8910万元(单位下同),同比增加1 2%;公司拥有人应占亏损约1 48亿元,同比收窄

2023-03-31

实打实举措 百分百贴心 ——宝安区以文明创建为民办实事 提升群众满意度

读特客户端·深圳新闻网2023年3月25日讯(深圳特区报记者陈震霖)“固戍一路改造后,我每天上下班都能节省不少时间,路面也平整了,出行更安全

2023-03-31

宜昌人才政策出“新招”:五年内人才综合投入将达70亿元 全面取消学历、年龄限制 天天讯息

3月29日至31日,首届宜昌“330”三峡国际人才日举办。值得关注的是,宜昌“1+4”人才政策3 0版也在近日同步印发。自2021年11月发布实施以来,

2023-03-31

劝阻男子在3岁女儿面前抽烟,父当街被刺杀满地血路人冷漠拍片

加拿大37岁父亲施密特(PaulStanleySchmidt)在咖啡店外发现一名男子正在抽电子烟,他只是要求对方不要在3岁女儿附近抽烟​,对方竟突然掏出小

2023-03-31

30元话费礼品卡

30元话费礼品卡,可以去看朋友,他家里有一个专门做的小东西,有一款卡片,他家人的家人物也不好用,而且也非常有心意。30元

2023-03-31

当前通讯!打通就诊 “最后一公里” 海岛居民有了数字化“急救专家”

打通就诊“最后一公里”海岛居民有了数字化“急救专家”---“这个情况我建议赶紧上岛救治,这边我们启动岛岛救了。”3月底,在舟山市定海区,

2023-03-31

Copyright ?  2015-2022 海峡科技网版权所有  备案号:皖ICP备2022009963号-10   联系邮箱:396 029 142 @qq.com