我的网站开发技术经验总结 我的网站开发技术经验总结
首页

fangdown

我的网站开发技术经验总结
首页
  • 大前端

  • 基础

  • 框架

  • 情商

  • 算法

    • 说说对二分查找的理解
    • 说说对动态规划、分而治之的理解
    • 说说对图的理解
    • 说说对堆的理解
      • 是什么
      • 分类
        • 大顶堆
        • 小顶堆
      • 操作
        • 插入
        • 删除
        • 复杂度
    • 说说对归并排序的理解
    • 说说对快速排序的理解
    • 说说对插入排序的理解
    • 说说对数据结构的理解
    • 说说对栈、队列的理解及应用
    • 说说对树(二叉树)的理解
    • 说说对算法的理解及应用场景
    • 说说对贪心算法,回溯算法的理解
    • 说说对选择排序的理解
    • 说说有哪些排序算法及理解
    • 说说算法复杂度有哪些?
    • 说说对冒泡排序的理解
  • 网络

  • 千锤百炼
  • 算法
fangdown
2021-10-15
目录

说说对堆的理解

# 是什么

堆: 通常可以看着一棵完全二叉树的数组对象

# 分类

  • 大顶堆
  • 小顶堆

# 大顶堆

每个节点的值都大于子树的节点值

# 小顶堆

每个节点的值都小于子树的节点值

# 操作

  • 插入
  • 删除

# 插入

  • 在数组尾部插入新值
  • 上移操作,直到父节点小于这个新值
// 插入元素
insert(value) {
  this.heap.push(value)
  this.shifUp(this.heap.length - 1)
}

// 上移操作
shiftUp(index) {
  if (index === 0) { return }
  const parentIndex = this.getParentIndex(index)
  if(this.heap[parentIndex] > this.heap[index]){
    this.swap(parentIndex, index)
    this.shiftUp(parentIndex)
  }
}

# 删除

  • 用数组尾部元素替换堆顶
  • 下移操作,和子节点进行交换, 直到子节点大于新堆顶
// 删除元素
pop() {
  this.heap[0] = this.heap.pop()
  this.shiftDown(0)
}

// 下移操作
shiftDown(index) {
  const leftIndex = this.getLeftIndex(index)
  const rightIndex = this.getRightIndex(index)
  if (this.heap[leftIndex] < this.heap[index]){
    this.swap(leftIndex, index)
    this.shiftDown(leftIndex)
  }
  if (this.heap[rightIndex] < this.heap[index]){
    this.swap(rightIndex, index)
    this.shiftDown(rightIndex)
  }
}

# 复杂度

Olog(n)

#算法
上次更新: 2021/12/19, 18:05:42
说说对图的理解
说说对归并排序的理解

← 说说对图的理解 说说对归并排序的理解→

最近更新
01
多分支修复撞车的问题
05-01
02
如何成为架构师
01-23
03
服务器部署全过程
11-23
更多文章>
Theme by Vdoing | Copyright © 2019-2026 fangdown | 粤ICP备19079809号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式