Skip to content

传送门

146. LRU 缓存

image.png

题解

image.png

javascript
// Vue3的keepalive组件就用了这个LRU管理组件的缓存
class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }

  get(key) {
    if (this.cache.has(key)) {
        // 存在即更新
        let temp = this.cache.get(key)
        this.cache.delete(key)
        this.cache.set(key, temp)
        return temp
    }
    return -1
  }

  put(key, value) {
    if (this.cache.has(key)) {
        // 存在即更新(删除后加入)
        this.cache.delete(key)
    } else if (this.cache.size === this.capacity) {
        // 不存在即加入
        // 缓存超过最大值,则移除最近没有使用的
      this.cache.delete(this.cache.keys().next().value);
    }
    this.cache.set(key, value);
  }
}
  • this.cache.keys().next().value 获取的是map结构中的第一个键
  • Map 中每个元素(键值对)的插入顺序是固定的,因此第一个插入的键位于 Map 的开头,也就是最开始插入的,最少使用的。

参考