继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【学习打卡】第23天 数据结构和算法

康遇
关注TA
已关注
手记 76
粉丝 3
获赞 9

JS实现最小堆

插入元素insert

  • 将值插入堆的底部(数组的尾部)
  • 执行上移操作:将这个值和父节点进行比较,直到父节点小于等于这个节点
  • 大小为k的堆的插入元素的时间复杂度是O(logk)

删除堆顶pop

  • 用数组尾部元素替换堆顶(直接删除堆顶会破坏堆的结构)
  • 执行下移操作:堆顶元素和子节点进行比较,直至子节点大于等于新堆顶元素
  • 大小为k的堆的删除堆顶的时间复杂度是O(logk)

获取堆顶peek

  • 返回数组的第一个元素

获取堆的长度size

  • 返回数组的长度
class MinHeap {
  constructor() {
    this.heap = [];
  }

  swap(i1, i2) {
    const temp = this.heap[i1];
    this.heap[i1] = this.heap[i2];
    this.heap[i2] = temp;
  }

  getParentIndex(index) {
    return Math.floor((index - 1) / 2);
  }

  getLeftIndex(index) {
    return index * 2 + 1;
  }

  getRightIndex(index) {
    return index * 2 + 2;
  }

  shiftUp(index) {
    if (index === 0) return
    const parentIndex = this.getParentIndex(index);
    if (this.heap[parentIndex] > this.heap[index]) {
      this.swap(index, parentIndex);
      this.shiftUp(parentIndex)
    }
  }

  shiftDown(index) {
    if (index === this.heap.length - 1) return;
    const leftIndex = this.getLeftIndex(index);
    const rightIndex = this.getRightIndex(index);
    if (this.heap[index] > this.heap[leftIndex]) {
      this.swap(index, leftIndex);
      this.shiftDown(leftIndex);
    }
    if (this.heap[index] > this.heap[rightIndex]) {
      this.swap(index, rightIndex);
      this.shiftDown(rightIndex);
    }
  }

  insert(val) {
    this.heap.push(val);
    this.shiftUp(this.heap.length - 1);
  }

  pop() {
    this.heap[0] = this.heap.pop();
    this.shiftDown(0);
  }

  peek() {
    return this.heap[0];
  }

  size() {
    return this.heap.length;
  }
}

const heap = new MinHeap();
// 添加顺序不同,生成的堆也不同
heap.insert(5)
heap.insert(4)
heap.insert(3)
heap.insert(2)
heap.insert(1)
heap.pop()

// heap.insert(1)
// heap.insert(2)
// heap.insert(3)
// heap.insert(4)
// heap.insert(5)
// heap.pop()
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP