LeetCode146 LRU 缓存机制

本文详细解析了LeetCode 146题的LRU缓存机制实现,使用JavaScript编写了一个双向链表结合哈希表的数据结构。在该实现中,通过双向链表保持缓存项的顺序,并利用哈希表快速查找节点,确保put和get操作的时间复杂度为O(1)。当缓存满时,会删除最近最少使用的节点。整个解决方案的空间复杂度为O(capacity)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode146 LRU 缓存机制

题目

在这里插入图片描述
在这里插入图片描述

解题:双向链表+散列表

在这里插入图片描述

// javascript
var DoubleLinkedListNode = function(key, value) {
    this.key = key;    // 记录 key
    this.val = value;
    this.prev = null;
    this.next = null;
};

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.cap = capacity;
    this.usedSpace = 0;
    this.cache = new Map();
    this.head = new DoubleLinkedListNode(undefined, undefined); // 伪头节点
    this.tail = new DoubleLinkedListNode(undefined, undefined); // 伪尾节点
    this.head.next = this.tail;
    this.tail.prev = this.head;
};

LRUCache.prototype.removeNode = function(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
    node.prev = null;
    node.next = null;
};

LRUCache.prototype.addToTail = function(node) {
    this.tail.prev.next = node;
    node.prev = this.tail.prev;
    this.tail.prev = node;
    node.next = this.tail;
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if (this.cache.has(key) === true) {
        let node = this.cache.get(key);
        // 把该节点移动到双向链表的末端
        this.removeNode(node);
        this.addToTail(node);
        return node.val;
    }
    return -1;
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
	// 如果存在,调用 get 将该节点移动到双向链表末端
    if (this.get(key) !== -1) {
        (this.cache.get(key)).val = value;
    } else {
    	// 如果双向链表已满,要先把最前面的节点删除
        if (this.usedSpace >= this.cap) {
            let delNode = this.head.next;
            this.removeNode(delNode);
            this.usedSpace--;
            this.cache.delete(delNode.key);
        }
        // 在双向链表的末端插入节点,cache 记录节点的地址
        let newNode = new DoubleLinkedListNode(key, value);
        this.addToTail(newNode);
        this.usedSpace++;
        this.cache.set(key, newNode);
    }
};

时间复杂度:对于 put 和 get 都是 O ( 1 ) O(1) O(1)

空间复杂度 O ( c a p a c i t y ) O(capacity) O(capacity)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值