审查 AI 写的滑动极值:双单调队列的九组 JavaScript 边界测试

10-19 5阅读

让 AI 写一个“最近一百个样本的最大值”,通常很快就能拿到带有单调队列的代码。危险之处在于:看上去使用了正确的数据结构,并不代表窗口语义已经正确。重复值可能被提前删除,拒绝的数据可能偷偷推进索引,长时间运行后计数器可能失去精度。一次漂亮的演示,无法替这些边界作证。

本文审查的是按成功接收的样本数量滑动的最小值与最大值。窗口宽度为 w,处理第 i 个有效样本后,只保留序号从 i−w+1 到 i 的已有样本。这里不使用时间戳,不讨论请求速率,也不根据真实时间间隔清理数据。两个样本相隔一秒还是一天,都不会改变窗口成员关系。

审查 AI 写的滑动极值:双单调队列的九组 JavaScript 边界测试
AI 生成的算法审查概念图:有限窗口、两条极值候选轨道与离开的旧样本。画面用于表达主题,轨道曲线不是实际数据、执行轨迹或单调性证明。

先把契约写在代码之前:只接受有限的 Number 原始值;NaN、正负无穷大和其他类型均拒绝;负零统一变为正零;相同极值选择索引较大的最新样本;预热阶段仍返回已有样本的结果,并用 ready 标记窗口是否填满。空状态的 peek 返回 null。失败输入不消耗位置,不淘汰任何旧样本。

宽度允许一到一百万之间的安全整数,这是本实现主动设置的资源边界,不是 JavaScript 的语言上限。默认索引从零开始;可选 startIndex 只改变新流的编号起点,不代表恢复了此前的窗口。最后一个允许的编号是 Number.MAX_SAFE_INTEGER,再次写入必须报错。这样“无限流”不会成为对无限精度或无限内存的隐含承诺。

全文恰有九个独立示例。把每个代码块分别保存为 01.mjs 到 09.mjs,使用 node --unhandled-rejections=strict 01.mjs 执行,其他编号同理。每段都包含所需定义,仅依赖 Node 内置断言模块;下方无语法高亮的文本是完整标准输出。本次在 Node v24.19.0 上逐段核对了退出码、标准错误和输出。该命令行选项让未处理的 Promise 拒绝进入未捕获异常路径,详见 Node 官方命令行文档。

一、先做一个故意慢的裁判

审查优化算法时,第一份代码最好足够直白:每次从窗口左端扫描到右端,逐一比较。它的时间开销是 O(nw),输出列表占 O(n) 空间,适合测试和小规模离线数据,不承担流式实现的性能目标。这里的参考函数只接收已经满足契约的有效数组和宽度;公共输入校验由后面的类负责。

注意参考循环使用小于等于和大于等于。因为扫描方向由旧到新,遇到相同值时覆盖索引,才能落实“最新者胜出”。只验证最小值和最大值两个数字,会漏掉重复值归属的错误。我们把值、来源索引、当前数量和预热状态都当作输出的一部分。

宽度为三时,第二个二取代第一个二成为最小值来源;五进入后,最大值更新;最后的一使最小值落到索引四。前三行也明确展示了不足窗口宽度时的行为。慢参考与快速实现必须先约定完全相同的语义,差分测试才具有解释力。

示例 01:独立保存为 01.mjs。

import assert from "node:assert/strict";
function reference(values, width, startIndex = 0) {
  const out = [];
  for (let i = 0; i < values.length; i++) {
    let min = Infinity, max = -Infinity, minIndex, maxIndex;
    for (let j = Math.max(0, i - width + 1); j <= i; j++) {
      const v = values[j] === 0 ? 0 : values[j];
      if (v <= min) { min = v; minIndex = startIndex + j; }
      if (v >= max) { max = v; maxIndex = startIndex + j; }
    }
    out.push({ min, max, minIndex, maxIndex,
      count: Math.min(i + 1, width), ready: i + 1 >= width });
  }
  return out;
}
const rows = reference([4, 2, 2, 5, 1], 3);
assert.equal(rows[2].minIndex, 2);
console.log(rows.map(r => `${r.min}/${r.max}@${r.minIndex}/${r.maxIndex}:${r.ready}`).join("\n"));

完整输出:

4/4@0/0:false
2/4@1/0:false
2/4@2/0:true
2/5@2/3:true
1/5@4/3:true

二、只有数值的队列会丢失身份

下面的程序是一个明确保留的错误反例。它在入队时压掉旧的相同最大值,却在过期时根据数值相等删除队首。对于两个连续的五,队列里只剩第二个五;当第一个五离开窗口,按值匹配的清理逻辑把仍然有效的第二个五一并删掉了。

这不是把比较符号换一下就能随意修好的问题。保留最早重复值与保留最新重复值都可以成为合法设计,但压缩规则、过期规则和返回索引必须一致。如果需求只返回数值,也仍然需要防止重复样本的身份被混淆。本实现将序号和值绑定在每个候选节点上,过期只看序号。

反例使用数组 shift 是为了把错误缩到几行,并不属于后续实现。断言要求它暴露错误结果,因此脚本正常退出不代表 brokenMax 可投入使用,而是说明这个最小反例已经稳定重现。请保留这样的失败样本,避免下一次 AI 重构又把它优化回来。

示例 02:独立保存为 02.mjs。

import assert from "node:assert/strict";
function brokenMax(values, width) {
  const q = [], out = [];
  for (let i = 0; i < values.length; i++) {
    if (i >= width && q[0] === values[i - width]) q.shift();
    while (q.length && q.at(-1) <= values[i]) q.pop();
    q.push(values[i]);
    out.push(q[0]);
  }
  return out;
}
const bad = brokenMax([5, 5, 1], 2).at(-1);
assert.equal(bad, 1);
assert.equal(Math.max(5, 1), 5);
console.log(`bad=${bad} expected=5`);

完整输出:

bad=1 expected=5

三、完整实现:两条候选队列与一个提交点

下面给出可直接运行的完整类。最小值队列从头到尾严格递增,最大值队列严格递减,两条队列中的索引都严格递增。队首始终是当前极值。新值进来时,先删除左边界以外的节点,再从尾部删除不可能重新成为答案的候选,最后追加新节点。

删除较差尾节点的理由是“支配关系”:对最小值而言,后来的更小或相等样本既不更差,又更晚过期,因此旧节点未来不会胜出。最大值完全对称。把相等也纳入删除条件,正好得到最新重复值政策。任何被保留节点的索引都在当前窗口内,边界合法性和数值单调性分别负责不同的正确性条件。

双向链表让头尾删除只修改相邻引用。删除时还显式断开旧节点的链接,避免把已淘汰的历史挂在活动链上。类的私有字段隐藏队列,peek 返回新的结果对象,sizes 只返回两个计数。调用方修改快照不会改变窗口;本实现没有向外暴露可修改的候选节点。

这里的提交点是校验通过之后的内部更新段。输入类型和索引耗尽检查都发生在删节点之前。后续步骤不调用用户提供的比较器、转换函数或回调,因而不会在普通输入处理中间重新进入窗口。我们承诺的是可预期校验失败不改状态,不是为内存耗尽或宿主崩溃提供数据库式回滚。

示例 03:独立保存为 03.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const window = new RollingExtrema(3);
assert.equal(window.peek(), null);
const rows = [4, 2, 2, 5, 1].map(v => window.push(v));
assert.deepEqual(rows.at(-1), {
  min: 1, max: 5, minIndex: 4, maxIndex: 3, count: 3, ready: true
});
console.log(rows.map(r => `${r.min}/${r.max}@${r.minIndex}/${r.maxIndex}:${r.ready}`).join("\n"));

完整输出:

4/4@0/0:false
2/4@1/0:false
2/4@2/0:true
2/5@2/3:true
1/5@4/3:true

四、重复值与淘汰边界必须一起核对

当前编号为 i、宽度为 w 时,最早仍允许的编号是 i−w+1。因此清理条件必须是 index 小于 left;等于 left 的样本仍在窗口内。如果写成小于等于,就会把窗口左端合法成员提前删除。等价的另一种表达是删除 index 小于等于 i−w,但不要把两个阈值混着使用。

本例把第二个七放在左边界上,让它在 left 等于一时必须保留,在 left 等于二时必须离开。仅用严格递增数据测试,常常看不出这个错误,因为更大的新值早已把队首替换。重复值与边界相遇,才是最容易暴露身份问题的组合。

连续相同值还揭示了政策对空间的影响:最新者胜出时,两条队列各保留一个候选即可。如果业务要求最早极值来源,就需要保留相同值,或设计明确的计数及索引结构,并同步修改参考模型。不能一边写着最早,一边为了减少节点而使用删除等值尾节点的条件。

示例 04:独立保存为 04.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const window = new RollingExtrema(3);
const rows = [7, 7, 1, 2, 3].map(v => window.push(v));
assert.equal(rows[1].maxIndex, 1);
assert.equal(rows[3].max, 7);
assert.equal(rows[3].maxIndex, 1);
assert.equal(rows[4].max, 3);
console.log(`ties: maxIndex=${rows[1].maxIndex}`);
console.log(`left=1: max=${rows[3].max}@${rows[3].maxIndex}`);
console.log(`left=2: max=${rows[4].max}@${rows[4].maxIndex}`);
const same = new RollingExtrema(5);
for (let i = 0; i < 20; i++) {
  const r = same.push(9);
  assert.equal(r.minIndex, i);
  assert.equal(r.maxIndex, i);
}
assert.deepEqual(same.sizes(), [1, 1]);
console.log("equal values: newest wins, sizes=1/1");

完整输出:

ties: maxIndex=1
left=1: max=7@1
left=2: max=3@4
equal values: newest wins, sizes=1/1

五、NaN、无穷大和负零不是附注

本实现选择拒绝所有非有限值。Number.isFinite 不会把字符串或包装对象转成数字,它的规范定义见 ECMAScript 的 Number.isFinite。这使校验不会触发对象的数值转换方法,也避免把空字符串或空值悄悄当成零。

选择拒绝 NaN,是为了不让“比较结果都为假”的值进入单调关系。正负无穷大在某些应用中也能有合理语义,但这里统一拒绝,以便调用方明确区分计算溢出、缺失值与正常观测。非常小和非常大的有限数仍然有效;算法只比较值,不进行求和,因此不会因累加产生新的数值溢出。

负零政策需要单独说清楚。输出将正负零统一为正零,而索引仍按最新样本选择。测试用 Object.is 检查符号,避免肉眼打印零时漏检;其基础是 Object.is 的 SameValue 语义。这不是宣称 JavaScript 的所有最小值运算都忽略负零,而是此接口主动采用的规范化约定。

示例 05:独立保存为 05.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const window = new RollingExtrema(2);
const invalid = [NaN, Infinity, -Infinity, "3", null, undefined,
  true, 1n, Symbol("x"), new Number(3)];
for (const v of invalid) assert.throws(() => window.push(v), TypeError);
assert.equal(window.peek(), null);
const zero = window.push(-0);
assert.equal(Object.is(zero.min, -0), false);
assert.equal(Object.is(zero.max, -0), false);
const tiny = window.push(Number.MIN_VALUE);
assert.equal(tiny.max, Number.MIN_VALUE);
const huge = window.push(Number.MAX_VALUE);
assert.equal(huge.max, Number.MAX_VALUE);
console.log(`rejected=${invalid.length}, empty=true`);
console.log(`zero: minNegative=${Object.is(zero.min, -0)}, maxNegative=${Object.is(zero.max, -0)}`);
console.log(`finite extremes accepted=${tiny.max > 0 && Number.isFinite(huge.max)}`);

完整输出:

rejected=10, empty=true
zero: minNegative=false, maxNegative=false
finite extremes accepted=true

六、拒绝一次输入,窗口应当像没见过它

“抛出异常”本身不等于失败原子性。若先推进序号、先淘汰队首,再检查 NaN,异常之后的窗口已经损坏。之后即使只写入合法数字,结果也可能与一开始就跳过错误输入的序列不同。审查时应沿着每条失败路径查找第一次状态写入,而不是只找有没有 throw。

本例先建立两个样本的完整窗口,再插入无效值,随后比较快照和候选计数。下一次合法输入必须使用编号二,旧的九必须恰好在这次离开,结果只能来自一和二。这个测试同时检查了失败后没有提前淘汰,也没有悄悄消耗索引。

构造参数也有明确限制,七种非法宽度逐一拒绝。这里不提供批量 pushAll,也不宣称多个 push 构成一个事务:调用方循环输入十个值,第六个失败时,前五个成功结果仍然存在。若业务需要整批原子提交,应先校验整批并定义溢出预检及内存预算,不能把单次写入保证直接推广成批处理保证。

示例 06:独立保存为 06.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const window = new RollingExtrema(2);
window.push(9); window.push(1);
const before = window.peek();
const sizes = window.sizes();
assert.throws(() => window.push(NaN), TypeError);
assert.deepEqual(window.peek(), before);
assert.deepEqual(window.sizes(), sizes);
const after = window.push(2);
assert.deepEqual(after, {
  min: 1, max: 2, minIndex: 1, maxIndex: 2, count: 2, ready: true
});
const copy = window.peek(); copy.max = 999;
assert.equal(window.peek().max, 2);
let rejectedWidths = 0;
for (const width of [0, -1, 1.5, NaN, Infinity, "2", 1_000_001]) {
  assert.throws(() => new RollingExtrema(width), RangeError);
  rejectedWidths++;
}
console.log("rejection preserved values, indices and sizes");
console.log(`next: ${after.min}/${after.max}@${after.minIndex}/${after.maxIndex}`);
console.log(`snapshot isolated=true, rejectedWidths=${rejectedWidths}`);

完整输出:

rejection preserved values, indices and sizes
next: 1/2@1/2
snapshot isolated=true, rejectedWidths=7

七、索引抵达精度边界时,停止比猜测可靠

长时间运行不意味着可以永远使用普通数字递增。安全整数上界是 9007199254740991;超过该范围,整数编号不再具有所需的唯一精确表示保证,依据见 ECMAScript 的安全整数上界定义。索引一旦重复或跳跃,淘汰逻辑就失去了可靠时间顺序。

实现允许写入最后一个安全编号,但不计算它的后继,而是设置耗尽标志。下一次有限值输入在任何修改之前被拒绝。测试通过 startIndex 把新流直接放到边界附近,省去不现实的长循环;这仅是编号偏移,不加载过去的样本,因此预热数量仍从零累计。

不要用按位运算压缩生产索引,也不要在溢出时擅自归零。归零必须同时处理所有候选索引和对外已经发出的索引,否则不同历史会重名。若产品确实要求更长编号,可以设计 BigInt 或分段编号接口,但那会改变序列化、比较成本和空间描述,必须成为新的契约与测试对象。

示例 07:独立保存为 07.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const last = Number.MAX_SAFE_INTEGER;
const window = new RollingExtrema(2, last - 1);
window.push(8);
const final = window.push(4);
assert.equal(final.minIndex, last);
assert.equal(final.maxIndex, last - 1);
const before = window.peek();
assert.throws(() => window.push(3), /index exhausted/);
assert.deepEqual(window.peek(), before);
assert.throws(() => new RollingExtrema(2, last + 1), RangeError);
assert.throws(() => new RollingExtrema(2, -1), RangeError);
console.log(`last: min@${final.minIndex}, max@${final.maxIndex}`);
console.log("overflow rejected before mutation");

完整输出:

last: min@9007199254740991, max@9007199254740990
overflow rejected before mutation

八、有界的是活动节点,不是进程内存曲线

每条候选链最多保留 w 个活动节点,两条合计不超过 2w。它们不保存完整历史,也没有一个不断增加头偏移、却从不整理的底层数组。sizes 用于暴露这个可测试的逻辑边界;链表删除同时更新两端并断开引用,代码审查则负责确认这些计数与实际可达结构一致。

四类长序列分别考验不同形状:递增输入让最小值链积满,递减输入让最大值链积满,交替输入反复改变尾部,完全相同的输入持续压缩等值节点。每一步都检查两条链的长度,最后再验证宽度为一的退化情况。只看最终长度不足以排除中途失控,因此约束要放在循环内部。

复杂度证明按节点的生命周期计数:一个样本在每条队列入队一次,之后最多被头部或尾部删除一次,处理 n 个样本总工作量为 O(n),单次为摊还 O(1)。但某次新值可能一口气删除许多尾节点,单次最坏仍为 O(w)。如果系统要求严格的尾延迟上界,不能把摊还常数时间写成每次恒定耗时。

这里的 O(w) 指窗口对象保留的活动状态。JavaScript 垃圾回收何时释放已不可达节点、进程堆预留多大,都不由该证明保证;调用方若保存所有返回快照,同样会额外占用 O(n) 空间。测试没有伪装成堆内存基准,也没有以一次运行时间推导所有机器的性能。

示例 08:独立保存为 08.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
const width = 64, length = 30_000;
const patterns = {
  increasing: i => i,
  decreasing: i => -i,
  alternating: i => i % 2 ? 1 : -1,
  equal: () => 6
};
for (const [name, valueAt] of Object.entries(patterns)) {
  const window = new RollingExtrema(width);
  for (let i = 0; i < length; i++) {
    window.push(valueAt(i));
    const [a, b] = window.sizes();
    assert.ok(a <= width && b <= width);
  }
  console.log(`${name}: ${window.sizes().join("/")}`);
}
const one = new RollingExtrema(1);
for (const value of [4, -2, 9, 9]) {
  const r = one.push(value);
  assert.equal(r.min, value); assert.equal(r.max, value);
  assert.equal(r.ready, true); assert.deepEqual(one.sizes(), [1, 1]);
}
console.log("width=1: passed; checked=120004 pushes");

完整输出:

increasing: 64/1
decreasing: 1/64
alternating: 2/1
equal: 1/1
width=1: passed; checked=120004 pushes

九、穷举小世界,再用固定种子扩大搜索

最后把完整实现与第一节的慢参考逐步对照。字母表包含负数、正数以及正负零;穷举长度零到六的所有序列,并对六种窗口宽度运行,覆盖空流、未填满窗口、大于序列长度的窗口和大量重复值。每个前缀都比较完整输出,不只比较最后一帧。

随后用固定种子生成两百条较长序列。这里的按位运算仅用于有意限定为三十二位的测试随机状态,与生产索引互不混用。固定种子让失败可以重放,但不会证明随机样本已经覆盖所有输入;小规模穷举、针对性边界样本与结构不变量承担不同职责,应当同时保留。

参考模型故意每次重新扫描,避免把同一个单调队列错误复制两遍。它仍然与被测实现共享接口契约,因此还需要前面那些手写预期:重复值选择、边界保留、负零规范化和耗尽行为。差分测试能发现实现不一致,不能替代对业务语义本身的判断。断言使用 Node 的严格模式,说明见 Node 官方断言文档。

示例 09:独立保存为 09.mjs。

import assert from "node:assert/strict";
class Deque {
  head = null; tail = null; size = 0;
  dropFront() {
    const old = this.head;
    this.head = old.next;
    if (this.head) this.head.prev = null;
    else this.tail = null;
    old.next = old.prev = null;
    this.size--;
  }
  dropBack() {
    const old = this.tail;
    this.tail = old.prev;
    if (this.tail) this.tail.next = null;
    else this.head = null;
    old.next = old.prev = null;
    this.size--;
  }
  expire(left) {
    while (this.head && this.head.index < left) this.dropFront();
  }
  append(index, value, isMin) {
    while (this.tail && (isMin
      ? this.tail.value >= value : this.tail.value <= value)) {
      this.dropBack();
    }
    const node = { index, value, prev: this.tail, next: null };
    if (this.tail) this.tail.next = node;
    else this.head = node;
    this.tail = node;
    this.size++;
  }
}
class RollingExtrema {
  #lo = new Deque(); #hi = new Deque();
  #width; #next; #count = 0; #exhausted = false;
  constructor(width, startIndex = 0) {
    if (!Number.isSafeInteger(width) || width < 1 || width > 1_000_000) {
      throw new RangeError("width must be 1..1000000");
    }
    if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
      throw new RangeError("invalid startIndex");
    }
    this.#width = width;
    this.#next = startIndex === 0 ? 0 : startIndex;
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite Number required");
    if (this.#exhausted) throw new RangeError("index exhausted");
    const x = value === 0 ? 0 : value;
    const i = this.#next;
    const left = i - this.#width + 1;
    this.#lo.expire(left);
    this.#hi.expire(left);
    this.#lo.append(i, x, true);
    this.#hi.append(i, x, false);
    this.#count = Math.min(this.#count + 1, this.#width);
    if (i === Number.MAX_SAFE_INTEGER) this.#exhausted = true;
    else this.#next = i + 1;
    return this.peek();
  }
  peek() {
    if (this.#count === 0) return null;
    return {
      min: this.#lo.head.value, max: this.#hi.head.value,
      minIndex: this.#lo.head.index, maxIndex: this.#hi.head.index,
      count: this.#count, ready: this.#count === this.#width
    };
  }
  sizes() { return [this.#lo.size, this.#hi.size]; }
}
function reference(values, width, startIndex = 0) {
  const out = [];
  for (let i = 0; i < values.length; i++) {
    let min = Infinity, max = -Infinity, minIndex, maxIndex;
    for (let j = Math.max(0, i - width + 1); j <= i; j++) {
      const v = values[j] === 0 ? 0 : values[j];
      if (v <= min) { min = v; minIndex = startIndex + j; }
      if (v >= max) { max = v; maxIndex = startIndex + j; }
    }
    out.push({ min, max, minIndex, maxIndex,
      count: Math.min(i + 1, width), ready: i + 1 >= width });
  }
  return out;
}
let streams = 0, pushes = 0;
function check(values, width) {
  const window = new RollingExtrema(width);
  const want = reference(values, width);
  assert.equal(window.peek(), null);
  for (let i = 0; i < values.length; i++) {
    assert.deepEqual(window.push(values[i]), want[i]);
    const [a, b] = window.sizes();
    assert.ok(a <= width && b <= width);
    pushes++;
  }
  streams++;
}
const alphabet = [-1, -0, 0, 2];
function enumerate(values, remaining) {
  for (let width = 1; width <= 6; width++) check(values, width);
  if (remaining === 0) return;
  for (const value of alphabet) enumerate([...values, value], remaining - 1);
}
enumerate([], 6);
let seed = 123456789;
function random() {
  seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
  return seed;
}
for (let round = 0; round < 200; round++) {
  const values = Array.from({ length: 100 }, () => random() % 31 - 15);
  check(values, random() % 30 + 1);
}
check([Number.MAX_VALUE, -Number.MAX_VALUE, Number.MIN_VALUE, -0, 0], 3);
console.log(`streams=${streams}, pushes=${pushes}`);
console.log("all outputs and candidate bounds match");

完整输出:

streams=32967, pushes=205693
all outputs and candidate bounds match

交付给 AI 的审查清单,应当能变成断言

这次审查的结论不是“单调队列比扫描快”这样一句口号,而是形成了一组可交付的约束:窗口按成功样本计数;极值和来源索引同时正确;最新重复值有确定优先级;左边界合法成员不被误删;无效输入完全不推进窗口;负零与非有限数政策公开;编号精度耗尽可预见;活动状态有上界;性能结论区分摊还与最坏情况。

让 AI 修改实现时,可以要求它为每一项变化指出受影响的断言。例如把重复值政策改为最早,需要同时修改尾部比较与参考模型;允许无穷大,需要更新校验与测试字母表;增加恢复接口,则要定义旧候选、计数和编号如何一并恢复。这样的变更说明比一段“已优化并修复边界”的总结更容易核验。

代码很短,契约却不能省略。真正适合长期运行的版本,不是永远不会报错的版本,而是在可接受的边界内持续给出可解释结果,并在越界前明确停止。本文的来源链接支持 JavaScript 和 Node 的语言及运行语义;单调队列的不变量、空间界限和差分结果则由这里公开的实现、论证与测试承担。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。