← 中文资源

简体中文版本

稳定同优先级的二叉最小堆

实现支持 push、pop、peek 的二叉最小堆,优先级相同时按插入顺序稳定出队,并用 JSON 操作序列驱动测试。

阅读英文原文

题目

实现 MinHeap 类,包含 push(item, priority)、pop() 和 peek()。pop 返回优先级最小的元素并将其移除;优先级相同时,必须先返回先插入的元素,即保持稳定。堆为空时 pop 与 peek 都返回 null。示例用 ops 数组描述 push、pop、peek 操作,最终输出按出队顺序排列的 item 列表,以及最后一次 peek 的结果(包含 item 和 priority)。

解题思路

每个堆元素保存 item、priority 和递增的 sequence。比较函数先比 priority,相等时再比 sequence,这样相同优先级天然按插入顺序排列。push 把元素追加到数组末尾,然后与父节点比较并上浮,直到父节点优先。pop 先记录根节点,再把最后一个元素移到根位置,删除末尾,然后与左右子节点中更优先的一个交换并下沉,直到满足堆序。

参考实现要点

下沉时必须先选出左右子节点中更优先的那个,再与当前节点比较,否则会破坏堆序。数组长度变化后要重新读取 size,避免使用过期长度。根节点被取出后,如果堆已空则不需要把任何元素移回根位置。peek 只返回副本,不能让调用方拿到内部对象而意外修改堆。sequence 只在 push 时递增,pop 后不复用。

常见错误

pop 时直接把根节点删除,没有把末尾元素移到根再下沉,会留下空洞并破坏完全二叉树性质。只比较 priority 而忽略 sequence,相同优先级出队顺序不稳定。下沉时只比较左子节点,右子节点更小时会选错。空堆 pop 返回 undefined 而不是约定好的 null,导致 JSON 输出出现缺项。

验证方式

逐个运行样例并比对 JSON。补充测试:连续压入多个相同优先级元素,出队顺序应与插入顺序一致;交替 push 与 pop 后,每次 pop 都是当前最小值;全部弹出后 peek 返回 null。还可以用随机序列与排序后的数组对比,确认堆序和稳定性始终成立。

代码示例

class MinHeap {
  #items = [];
  #sequence = 0;

  #before(a, b) {
    return a.priority < b.priority ||
      (a.priority === b.priority && a.sequence < b.sequence);
  }

  #swap(i, j) {
    const temp = this.#items[i];
    this.#items[i] = this.#items[j];
    this.#items[j] = temp;
  }

  #up(index) {
    let current = index;
    while (current > 0) {
      const parent = (current - 1) >> 1;
      if (!this.#before(this.#items[current], this.#items[parent])) break;
      this.#swap(current, parent);
      current = parent;
    }
  }

  #down(index) {
    let current = index;
    const size = this.#items.length;
    while (true) {
      const left = current * 2 + 1;
      const right = left + 1;
      let best = current;
      if (left < size && this.#before(this.#items[left], this.#items[best])) best = left;
      if (right < size && this.#before(this.#items[right], this.#items[best])) best = right;
      if (best === current) break;
      this.#swap(current, best);
      current = best;
    }
  }

  push(item, priority) {
    this.#items.push({ item, priority, sequence: this.#sequence++ });
    this.#up(this.#items.length - 1);
    return this;
  }

  peek() {
    if (this.#items.length === 0) return null;
    const top = this.#items[0];
    return { item: top.item, priority: top.priority };
  }

  pop() {
    if (this.#items.length === 0) return null;
    const top = this.#items[0];
    const last = this.#items.pop();
    if (last && this.#items.length > 0) {
      this.#items[0] = last;
      this.#down(0);
    }
    return { item: top.item, priority: top.priority };
  }
}

const payload = JSON.parse(input);
const heap = new MinHeap();
const popped = [];
let peek = null;
for (const op of payload.ops) {
  if (op.op === 'push') heap.push(op.item, op.priority);
  else if (op.op === 'pop') {
    const entry = heap.pop();
    popped.push(entry ? entry.item : null);
  } else if (op.op === 'peek') peek = heap.peek();
}
console.log(JSON.stringify({ popped, peek }));