← 中文资源

简体中文版本

带比较器的泛型优先队列

实现支持任意元素类型与自定义比较器的二叉小顶堆优先队列,并提供 push、pop、peek 与 size。

阅读英文原文

题目

实现一个泛型 PriorityQueue 类,底层使用二叉堆。构造函数接收比较器,返回负数表示第一个参数应优先出队。需要支持 push 入队、pop 取出并返回最小元素、peek 查看堆顶、size 返回元素个数。随后按顺序重放操作数组,把 pop 与 peek 的返回值收集成结果;队列为空时用字符串 empty 表示。

解题思路

元素存放在数组中,按完全二叉树的层序组织。push 把新元素追加到末尾,然后不断与父节点比较并上浮,直到满足堆序。pop 取出堆顶,把末尾元素移到根部,再与较小子节点比较并下沉。两种操作都保持 O(log n),peek 与 size 为 O(1)。m 次操作总时间为 O(m log n),空间为 O(n)。

把比较逻辑抽成注入的比较器,是泛型设计的关键:同一份堆代码可以处理数字升序、任务截止时间或字符串长度等不同排序规则,而无需修改结构本身。

参考实现要点

比较器保存在私有字段中,构造函数负责赋值,避免在方法里重复解构。上浮只与父节点比较,下标用 (index-1)>>1 计算。下沉时先选出左右子节点中较小的一个,再决定是否交换。空堆 pop 返回 undefined,重放函数再把它转换成 empty 字符串。

常见错误

直接用小于号比较元素,遇到对象类型时无法工作,也违背了泛型设计。忘记在 pop 后判断堆是否为空,会对 undefined 继续下沉。另一个错误是下沉时只比较左孩子,忽略右孩子更小的情况。比较器的方向写反会把小顶堆变成大顶堆。

验证方式

样例覆盖正常出队顺序、空队列弹出与 peek、以及连续取出直到为空三种情况。再检查混合操作后 size 是否准确、peek 是否不删除元素。最后传入 (a,b)=>b-a 作为比较器,确认结构变成大顶堆,并用对象元素验证类型推断。

代码示例

type Comparator<T> = (a: T, b: T) => number;

class PriorityQueue<T> {
  private heap: T[] = [];
  private compare: Comparator<T>;

  constructor(compare: Comparator<T>) {
    this.compare = compare;
  }

  get size(): number {
    return this.heap.length;
  }

  peek(): T | undefined {
    return this.heap[0];
  }

  push(value: T): void {
    this.heap.push(value);
    this.siftUp(this.heap.length - 1);
  }

  pop(): T | undefined {
    if (this.heap.length === 0) return undefined;
    const top = this.heap[0];
    const last = this.heap.pop() as T;
    if (this.heap.length > 0) {
      this.heap[0] = last;
      this.siftDown(0);
    }
    return top;
  }

  private siftUp(index: number): void {
    while (index > 0) {
      const parent = (index - 1) >> 1;
      if (this.compare(this.heap[index], this.heap[parent]) >= 0) break;
      [this.heap[index], this.heap[parent]] = [this.heap[parent], this.heap[index]];
      index = parent;
    }
  }

  private siftDown(index: number): void {
    const length = this.heap.length;
    for (;;) {
      const left = index * 2 + 1;
      const right = left + 1;
      let smallest = index;
      if (left < length && this.compare(this.heap[left], this.heap[smallest]) < 0) {
        smallest = left;
      }
      if (right < length && this.compare(this.heap[right], this.heap[smallest]) < 0) {
        smallest = right;
      }
      if (smallest === index) break;
      [this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
      index = smallest;
    }
  }
}

function runPriorityQueue(operations: Array<[string, number?]>): Array<number | string> {
  const queue = new PriorityQueue<number>((a, b) => a - b);
  const output: Array<number | string> = [];

  for (const [operation, value] of operations) {
    if (operation === "push") {
      queue.push(value as number);
    } else if (operation === "pop") {
      const popped = queue.pop();
      output.push(popped === undefined ? "empty" : popped);
    } else if (operation === "peek") {
      const top = queue.peek();
      output.push(top === undefined ? "empty" : top);
    }
  }

  return output;
}