LRU 缓存结构

文章目录

LRU

  • 优先去除最久没有访问到的数据。

实现

  • 通过组合哈希表(Hash Table)和双向链表(Doubly Linked List)实现 LRU 缓存。并且以 O(1) 的时间复杂度执行 get 和 put 操作
  • 核心是对节点的新增、访问都会让节点移动到双向链表头部,当容量超过时,直接删除尾部节点即可
javascript 复制代码
class LRUCache {
  constructor(capacity) {
    // 容量
    this.capacity = capacity;
    this.cache = new Map();

    // 用于记录访问顺序的双向链表,声明空的头节点和尾节点
    this.head = {};
    this.tail = {};
    // 头和尾相连
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }

  get(key) {
    const map = this.cache;

    if (!map.has(key)) {
      return -1;
    }
	// 每次把使用的节点放到链表的头部
    const node = map.get(key);
    this._moveToHead(node);
    return node.value;
  }

  put(key, value) {
    const map = this.cache;
    
    // 如果 key 已存在,更新并移动到双向链表头部
    if (map.has(key)) {
      const node = map.get(key);
      node.value = value;
      this._moveToHead(node);
    } else {
      if (map.size >= this.capacity) {
        // 缓存容量已满,移除尾部节点
        const leastUsedKey = this.tail.prev.key;
        this._removeNode(this.tail.prev);
        map.delete(leastUsedKey);
      }

      // 创建新节点,和更新 HashMap,并移动到链表头部
      const newNode = this._addNode({ key, value });
      map.set(key, newNode);
    }
  }
  // 双向链表删除节点
  _removeNode(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
  }
 // 删除双向链表旧节点位置,然后移动到头部
  _moveToHead(node) {
    this._removeNode(node);
    this._addNode(node);
  }
 // 添加节点并移动到头部
  _addNode(node) {
    node.prev = this.head;
    node.next = this.head.next;
    this.head.next.prev = node;
    this.head.next = node;
    return node;
  }
}

// 使用示例
const cache = new LRUCache(2);
cache.put(1, 10);
console.log(cache.get(1)); // 10
cache.put(2, 20);
cache.put(3, 30);
console.log(cache.get(1)); // -1
相关推荐
csdn_aspnet7 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
c++·算法
逐米时代9 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践
人工智能·算法·制造
kyrie_sakura10 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
Rabitebla10 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法
星栈10 小时前
我在浏览器里试了试 PhotoCraft|Rust + WASM 修图,是玩具还是生产力?
前端
m0_7431064611 小时前
SAD-GS:从梯度邻域到频率驱动表达3D空间
人工智能·算法·计算机视觉·3d·几何学
爪哇碎碎念11 小时前
【Java】从一次 cache.get(key) 进去:缓存击穿一瞬间打出 200 次 DB,JDK 17 实测三种解法
java·redis·缓存
csdn_aspnet11 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
雨中飘荡的记忆11 小时前
淘宝搜不到的东西,能不能去全世界找?一个程序员的创业尝试
前端·设计
kyriewen12 小时前
我让 4 位 AI 面试官打分,同一个我差了 40 分
前端·面试·程序员