← 中文资源

简体中文版本

带驱逐日志的泛型 LRU 缓存

用泛型键值实现固定容量 LRU 缓存,读取时提升优先级,写入时按最久未使用顺序驱逐,并记录每次被淘汰的键值对。

阅读英文原文

题目

实现泛型类 LRUCache<K, V>,容量必须为正整数。get 返回对应的值并把该键提升为最近使用;set 插入或更新键值,缓存已满且键不存在时驱逐最久未使用的条目;delete 删除键;entries 按最久未使用到最近使用的顺序返回键值对。每次驱逐都要把被淘汰的键和值记录下来,示例最终输出 gets、evicted 与 entries。

解题思路

Map 的插入顺序就是优先级顺序:队首最旧,队尾最新。get 命中后先保存值,再 delete 并重新 set,把键移动到末尾;未命中返回 undefined。set 分两种情况:键已存在时先删除旧条目,不触发驱逐;键不存在且容量已满时,用 this.data.keys().next() 取最旧的键,先读出它的值,再删除并连同值一起写入驱逐日志。最后把新键值追加到末尾。

参考实现要点

驱逐日志必须在删除之前读取被淘汰的值,否则只能记录键而丢失值。更新已有键时不要走容量判断,否则会误驱逐其他条目。entries 使用展开后的 Map 条目数组,顺序即 LRU 到 MRU。容量小于 1 时在构造阶段抛出 RangeError,避免后续行为不确定。drainEvicted 返回日志后清空,便于分别断言。

常见错误

get 命中后只读取不重新插入,缓存会退化成 FIFO,热点键被过早淘汰。更新已有键时没有先删除,Map 中键的位置不会更新,优先级仍旧。驱逐时先删除再取值,evicted 里会出现 undefined。把 entries 按值排序或反转,输出顺序与约定不符。

验证方式

用 tsc –strict 编译,确认键值类型被保留。运行三个样例并比对 JSON。补充测试:容量为 0 时构造应抛错;删除不存在的键返回 false 且不产生驱逐记录;对同一个键反复 set 不应驱逐其他键。最后检查任意时刻 entries 长度不超过容量,且插入总数等于当前条目数加驱逐数。

代码示例

declare const input: string;

class LRUCache<K, V> {
  private readonly data = new Map<K, V>();
  private readonly capacity: number;
  private evicted: Array<[K, V]> = [];

  constructor(capacity: number) {
    if (capacity < 1) throw new RangeError('capacity must be >= 1');
    this.capacity = capacity;
  }

  get(key: K): V | undefined {
    if (!this.data.has(key)) return undefined;
    const value = this.data.get(key) as V;
    this.data.delete(key);
    this.data.set(key, value);
    return value;
  }

  set(key: K, value: V): void {
    if (this.data.has(key)) {
      this.data.delete(key);
    } else if (this.data.size >= this.capacity) {
      const oldest = this.data.keys().next();
      if (!oldest.done) {
        const evictedKey = oldest.value;
        const evictedValue = this.data.get(evictedKey) as V;
        this.data.delete(evictedKey);
        this.evicted.push([evictedKey, evictedValue]);
      }
    }
    this.data.set(key, value);
  }

  delete(key: K): boolean {
    return this.data.delete(key);
  }

  entries(): Array<[K, V]> {
    return [...this.data.entries()];
  }

  drainEvicted(): Array<[K, V]> {
    const drained = this.evicted;
    this.evicted = [];
    return drained;
  }
}

interface Spec {
  capacity: number;
  ops: Array<
    | { op: 'set'; key: string; value: number }
    | { op: 'get'; key: string }
    | { op: 'delete'; key: string }
  >;
}

const spec = JSON.parse(input) as Spec;
const cache = new LRUCache<string, number>(spec.capacity);
const gets: Array<number | null> = [];

for (const op of spec.ops) {
  if (op.op === 'set') cache.set(op.key, op.value);
  else if (op.op === 'get') gets.push(cache.get(op.key) ?? null);
  else cache.delete(op.key);
}

console.log(JSON.stringify({ gets, evicted: cache.drainEvicted(), entries: cache.entries() }));