JavaScript 的 LRU缓存实现
等级 5546 次按键
LRU缓存在超过容量时淘汰最近最少使用的项。
JavaScript 代码
// 使用Map的LRU(最近最少使用)缓存1class LRUCache {2 constructor(capacity) { // 设置最大项数3 this.capacity = capacity; // Map保持插入顺序4 this.cache = new Map();5 }6 get(key) { // 如果键不存在返回-17 if (!this.cache.has(key)) return -1; // 获取值8 const val = this.cache.get(key); // 通过重新插入移动到末尾(最近使用)9 this.cache.delete(key);10 this.cache.set(key, val);11 return val;12 }13 put(key, value) { // 如果存在则删除(更新位置)14 this.cache.delete(key); // 添加到末尾(最近使用)15 this.cache.set(key, value); // 如果超过容量,删除最旧(第一个)项16 if (this.cache.size > this.capacity) { // keys().next().value是第一个(最旧的)键17 this.cache.delete(this.cache.keys().next().value);18 }19 }20}21 // 创建容量为2的缓存22const cache = new LRUCache(2);// 添加项23cache.put(1, "a"); cache.put(2, "b");// 获取1(使其成为最近使用)24console.log(cache.get(1));// 添加3,淘汰2(最近最少使用)25cache.put(3, "c");// 2被淘汰,返回-126console.log(cache.get(2));运行结果
a -1
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
.× 30(× 23)× 23;× 16,× 6"× 6{× 5}× 5=× 4-× 1