【力扣hot100题】(133)LRU缓存

看了很久才知道是什么意思......

哈希表+双向链表,注意哈希表存放的对应关系是key和链表节点的,而链表节点存储value。

注意一下链表需要设置头尾指针。

cpp 复制代码
class LRUCache {
public:
    struct ListNode{
        int key,val;
        ListNode* next;
        ListNode* prev;
        ListNode():key(0),val(0),next(nullptr),prev(nullptr){}
        ListNode(int key,int value,ListNode* next=nullptr,ListNode* prev=nullptr):key(key),val(value),next(next),prev(prev){}
    };
    ListNode* head;
    ListNode* tail;
    int capacity;
    unordered_map<int,ListNode*> hash;
    LRUCache(int capacity) {
        this->capacity=capacity;
        head=new ListNode();
        tail=new ListNode(0,0,nullptr,head);
        head->next=tail;
    }
    
    int get(int key) {
        if(hash.find(key)==hash.end()) return -1;
        ListNode* g=hash[key];
        g->next->prev=g->prev;
        g->prev->next=g->next;
        head->next->prev=g;
        g->next=head->next;
        g->prev=head;
        head->next=g;
        return g->val;
    }
    
    void put(int key, int value) {
        if(hash.find(key)!=hash.end()){
            hash[key]->val=value;
            int k=get(key);
            return;
        }
        if(capacity>0) capacity--;
        else{
            ListNode* t=tail->prev;
            tail->prev=tail->prev->prev;
            tail->prev->next=tail;
            hash.erase(t->key);
        }
        ListNode* n=new ListNode(key,value,head->next,nullptr);
        head->next->prev=n;
        n->prev=head;
        head->next=n;
        hash[key]=n;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
相关推荐
Chenyu_3108 小时前
DPDK、TC 和 XDP:Linux 高性能网络到底在优化什么
linux·服务器·网络·缓存
DongQiShanRen9 小时前
六根硬件映射(四):归属澄清、两处不一致与卷十一总表
开发语言·人工智能·算法·rust·哈希算法·集成学习
Nil20812 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_6745719712 小时前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂13 小时前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin77014 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
DongQiShanRen20 小时前
六根硬件映射(下):物理闭环五步法,抽一条已实装的看
大数据·jvm·人工智能·算法·rust·哈希算法·集成学习
hflmwl821 小时前
RedisDesktopManager安装包中文版官方下载,redis可视化客户端工具下载
数据库·redis·缓存·可视化客户端工具
alphaTao21 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
一枕槐安48721 小时前
大模型应用后端设计:上下文管理、缓存、降级策略的工程方案总结
java·spring·缓存