leetcode 146: LRU Cache

本文介绍了如何使用无序映射和双向链表实现LRU(最近最少使用)缓存策略,详细解释了数据结构的设计和实现过程,包括节点的创建、缓存获取和设置操作。

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

Use an unordered map and a doubly linked list to implement.

struct Node{
    int key;
    int value;
    Node* next;
    Node* pre;
    Node(int k,int v){
        key=k;
        value=v;
        pre=next=NULL;
    }
};
class LRUCache{
public:
    LRUCache(int capacity) {
        cap=capacity;
        cachesize=0;
        head=new Node(0,0);
        tail=new Node(0,0);
        head->next=tail;
        tail->pre=head;
    }
    
    int get(int key) {
        if(mp.find(key)!=mp.end())
        {
            Node *p=mp[key];
            p->next->pre=p->pre;
            p->pre->next=p->next;
            
            p->pre=tail->pre;
            tail->pre->next=p;
            p->next=tail;
            tail->pre=p;
            return mp[key]->value;
        }
        return -1;
    }
    
    void set(int key, int value) {
        unordered_map<int,Node*>::iterator it=mp.find(key);
        if(it!=mp.end())
        {
            Node *p=mp[key];
            p->next->pre=p->pre;
            p->pre->next=p->next;
            p->value=value;
            
            p->pre=tail->pre;
            tail->pre->next=p;
            p->next=tail;
            tail->pre=p;
        }
        else
        {
            if(cachesize==cap)
            {
                it=mp.find(head->next->key);
                Node *p=head->next;
                head->next->next->pre=head;
                head->next=head->next->next;
                delete p;
                mp.erase(it);
                cachesize--;
            }
            Node *p=new Node(key,value);
            p->pre=tail->pre;
            tail->pre->next=p;
            p->next=tail;
            tail->pre=p;
            mp.insert(make_pair(key,p));
            cachesize++;
        }
    }
private:
    unordered_map<int,Node*> mp;
    Node* head;
    Node* tail;
    int cachesize;
    int cap;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值