【力扣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);
 */
相关推荐
To_OC5 天前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC5 天前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
To_OC6 天前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
To_OC6 天前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
To_OC7 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
To_OC9 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
小七-七牛开发者9 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
To_OC10 天前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
ofoxcoding16 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
想吃火锅100516 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展