zoukankan      html  css  js  c++  java
  • 创建堆(python)

    创建最大(小)堆

    二叉堆本质上是一种完全二叉树,存储方式并不是链式存储,而是顺序存储

    • 堆操作:插入(叶子节点上调),删除(堆顶元素下沉)

    • 堆创建:非叶子节点下沉(从最后一个非叶子节点开始)

      • 最小堆:

        最小堆任何一个父节点的值,都小于等于它左右孩子节点的值

        创建过程:如果非叶子节点值大于其子节点,将其下沉

      • 最大堆:

        最大堆任何一个父节点的值,都大于等于它左右孩子节点的值。

        创建过程:如果非叶子节点值小于其子节点,将其下沉

    #最小堆
    def upadjust(nums):
        childindex = len(nums)-1
        parentindex = (childindex-1)//2
        temp = nums[childindex] #插入的叶子节点值
        while childindex>0 and temp<nums[parentindex]:#子节点小于父节点,上调子节点
            nums[childindex] = nums[parentindex]
            childindex = parentindex
            parentindex = (parentindex-1)//2
        nums[childindex] = temp
    
    def downadjust(nums,parentindex):
        temp = nums[parentindex]
        childindex = 2*parentindex + 1
        while childindex < len(nums):
            #右孩子值小于左孩子,父节点和小的交换
            if childindex +1 <len(nums) and nums[childindex+1] < nums[childindex]:
                childindex += 1
            if temp < nums[childindex]:    #父节点小于子节点,不用调整
                break
            nums[parentindex] = nums[childindex]
            parentindex = childindex
            childindex = childindex*2+1
        nums[parentindex] = temp
    
    def buildMinHeap(nums):
        for i in range((len(nums)-1)//2,-1,-1):
            downadjust(nums,i)
    
    >>> nums = [5,8,6,3,9,2,1,7,0]
    >>> buildMinHeap(nums)
    >>> nums
    [0, 5, 6, 8, 9, 2, 1, 7, 3]
    
    #最大堆
    #非叶子节点小值下沉
    def downadjust(nums,parentindex):
        temp = nums[parentindex]
        childindex = 2*parentindex + 1
        while childindex < len(nums):
            if childindex +1 <len(nums) and nums[childindex+1] > nums[childindex]:#右孩子值大于左孩子,父节点和大的交换
                childindex += 1
            if temp > nums[childindex]:    #父节点大于子节点,不用调整
                break
            nums[parentindex] = nums[childindex]
            parentindex = childindex
            childindex = childindex*2+1
        nums[parentindex] = temp
    
    def buildMaxHeap(nums):
        for i in range((len(nums)-1)//2,-1,-1):
            downadjust(nums,i)
    
    >>> nums = [5,8,6,3,9,2,1,7,0]
    >>> buildMaxHeap(nums)
    >>> nums
    [9, 8, 6, 7, 5, 2, 1, 3, 0]
    

    python自带堆模块

    >>> import heapq
    #默认最小堆
    >>> nums = [5,8,6,3,9,2,1,7,0]
    >>> heapq.heapify(nums)
    >>> nums
    [0, 3, 1, 5, 9, 2, 6, 7, 8]
    
  • 相关阅读:
    C++ 对象没有显式初始化
    NFA与DFA
    VS DLL 复制本地
    TFS 图标意思
    C++ 析构方法
    C++ 异常
    【转】二叉树的非递归遍历
    【转】Dijkstra算法(单源最短路径)
    Dijkstra最短路径算法
    python __name__
  • 原文地址:https://www.cnblogs.com/gongyanzh/p/12703969.html
Copyright © 2011-2022 走看看