题目
实现 LRUCache 类,容量固定,get 与 put 均为 O(1),超出容量时淘汰最久未使用的键。输入契约为容量数字,输出契约为带 get(key) 与 put(key, value) 的缓存实例。样例容量 2,依次 put(1,1)、put(2,2)、get(1)、put(3,3)、get(2),得到 1 与 -1;容量 1 时后写入会淘汰先写入。
解题思路
用 Map 保存键值,并利用 Map 按插入顺序迭代的特性:末尾是最近使用的键,开头是最久未使用的键。get 命中后先删除再重新写入,把该键移到末尾;put 先删除同名键再写入,容量超限时删除 Map 的第一个键。
参考实现要点
this.cache.keys().next().value 取得第一个键作为淘汰对象。只有在 size 超过 capacity 时才执行淘汰。get 未命中返回 -1。删除再插入同时更新值与顺序,Map 的访问、删除与插入都是常数时间。
常见错误
原文指出:get 命中后不把键移到末尾,会破坏 LRU 顺序。另一个相关问题是容量为 0 时每次 put 都会立即触发淘汰,边界情况需要确认行为符合预期。
验证方式
用 Node.js 运行,按样例序列调用并断言返回值;再测容量 1、重复写入同一键与容量为 0 的情况,确认淘汰与顺序更新正确。
代码示例
class LRUCache {
constructor(capacity) { this.capacity = capacity; this.cache = new Map(); }
get(key) {
if (!this.cache.has(key)) return -1;
const val = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, val);
return val;
}
put(key, value) {
if (this.cache.has(key)) this.cache.delete(key);
this.cache.set(key, value);
if (this.cache.size > this.capacity) {
const oldest = this.cache.keys().next().value;
this.cache.delete(oldest);
}
}
}