LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.


pro:
实现一个LRU Cache,要求能根据key做get操作,返回其value;能对给出的key,value如果之前的key存在,则设置value;不存在则如果Cache的容量尚有多余,直接插入,否则要淘汰最近最少用的数据,再将其插入。无论是set还是get,都视这个数据是最新被使用过。
sol:
可以预见,删除插入比较多,要做到O(1),就需要使用链表,需要记录最后的节点(最旧的)以便删除,又需要将新节点或者最近访问的节点插入到表头后,因此需要双向链表。get的时候又需要O(1)定位,所以需要一个map,从key指向链表的节点。有了这两个数据结构就OK了~!
trick:
双向链表的删除和插入操作是基础啊~!!分别影响两条线和四条线。

code:

struct ListNodee
{
    int key;
    int val;
    ListNodee *next;
    ListNodee *pre;
    ListNodee(int x,int y):key(x),val(y),next(NULL),pre(NULL){}
};

class LRUCache{
private:
    int capacity;
    map<int,ListNodee*> mymap;
    ListNodee *root;
    ListNodee *lastone;
    int current;
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
        this->mymap.clear();
        this->root = new ListNodee(0,0);
        this->lastone = root;
        this->current = 0;
    }
    
    int get(int key) {
        if(mymap.find(key)==mymap.end()) return -1;
        else
        {
            ListNodee* temp = mymap[key];
            makeTop(root,temp);
            return temp->val;
        }
    }
    void deletion(ListNodee *root,ListNodee *mynode)
    {
        //delete from map
        map<int,ListNodee*>::iterator it;
        it = mymap.find(mynode->key);
        mymap.erase(it);
        
        if(mynode->next==NULL) this->lastone = mynode->pre;
        this->current--;
        mynode->pre->next = mynode->next;
        if(mynode->next!=NULL)//forgot added!!!!!!!
            mynode->next->pre = mynode->pre;//forgot added!!!!!!!
    }
    void makeTop(ListNodee *root,ListNodee *mynode)
    {
        deletion(root,mynode);
        insert(this->root,mynode);
    }
    void insert(ListNodee *root,ListNodee *mynode)
    {
        this->current++;
        mynode->pre = root;
        mynode->next = root->next;
        if(root->next!=NULL)
            root->next->pre = mynode;
        root->next = mynode;
        if(mynode->next == NULL) this->lastone = mynode;//forgot added!!!!!!!
        mymap[mynode->key] = mynode;
    }
    
    void set(int key, int value) {
        if(mymap.find((key))!=mymap.end())
        {
            ListNodee *temp = mymap[key];
            temp->val = value;
            makeTop(root,temp);
        }else
        {
            ListNodee *newnode = new ListNodee(key,value);
            if(this->current<this->capacity)
            {
                insert(this->root,newnode);
            }else
            {
                //remove oldest,insert new,remove in map,update variables
                deletion(this->root,this->lastone);
                insert(this->root,newnode);
            }
        }
    }
};




<think>好的,用户想了解LRU缓存的工作原理和实现方法。首先,我需要回忆LRU的基本概念,确定LRU是Least Recently Used的缩写,即最近最少使用算法,常用于缓存淘汰策略。接下来,工作原理部分需要解释当缓存容量满时,如何选择最久未被访问的数据进行淘汰。这里可能需要结合数据结构,比如哈希表和双向链表,来说明如何高效地实现访问顺序的维护。 然后是具体实现方法。常见的实现方式确实是用哈希表加双向链表。哈希表用于快速定位节点,双向链表则维护访问顺序。最近访问的节点移到链表头部,最久未使用的在尾部。当插入新数据时,如果缓存已满,就删除尾部节点。这部分需要详细说明每个操作的步骤,比如访问、插入、删除等,以及它们的时间复杂度。 可能还需要提到其他实现方式,比如使用OrderedDict的数据结构,这在Python中确实存在,可以简化实现。但如果是其他语言,可能需要自己构建双向链表和哈希表。这部分可以作为不同实现方法的补充说明。 接下来,用户可能关心LRU的应用场景,比如数据库缓存、页面置换算法等,但用户的问题主要集中在实现和工作原理,所以这部分可能不需要深入,但可以作为相关问题提出。 然后,根据用户提供的引用,我需要检查是否有相关引用可以支持回答。但查看用户提供的引用内容,引用1是关于流处理和响应式编程的库,引用2是机器学习在GPU集群调度的应用,引用3是Go语言编译工具,似乎和LRU缓存没有直接关联。因此,可能无法直接引用这些内容,需要忽略引用部分,或者寻找间接关联点,但可能不太相关。 在生成相关问题的时候,需要考虑用户可能进一步想了解的内容,比如LRU的变种、时间复杂度分析、实际应用中的挑战、与其他算法比较等。例如,如何保证O(1)时间复杂度,如何处理并发访问,LRU的缺点以及改进算法如LRU-K等。 最后,代码示例部分需要确保正确性。Python中使用OrderedDict是一个典型的实现方式,每次访问时移动键到最新位置,插入时检查容量并弹出最久未使用的项。需要确保代码示例简洁,并且注释清晰,方便用户理解。 总结整个思考过程,需要将LRU的工作原理和实现方法清晰地分点解释,结合数据结构和操作步骤,给出代码示例,并生成相关问题,引导用户深入理解。同时注意用户提到的系统级指令,如数学公式的正确格式,但LRU内容可能较少涉及数学公式,所以主要关注代码块和结构。</think>### LRU缓存实现原理 LRU(Least Recently Used)缓存淘汰策略基于"最近最少使用"原则,当缓存容量满时淘汰最久未被访问的数据。其核心数据结构组合为: 1. **哈希表**:实现$O(1)$时间复杂度的键值查询 2. **双向链表**:维护键的访问顺序,最近访问的节点靠近头部 ### 操作过程 1. **访问数据**: - 通过哈希表定位节点 - 将节点移动到链表头部(表示最近使用) - 时间复杂度:$O(1)$ 2. **插入数据**: ```python if 键已存在: 更新值并移动节点到链表头部 else: 创建新节点并添加到链表头部 if 缓存已满: 删除链表尾部节点 从哈希表删除对应键 ``` ### Python实现示例 ```python from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) ``` ### 性能特征 - **时间复杂度**:所有操作保持$O(1)$ - **空间复杂度**:$O(n)$,n为缓存容量 - **适用场景**:符合局部性原理的访问模式,如数据库缓存、CDN缓存等[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值