【力扣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);
 */
相关推荐
Dream it possible!18 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊18 小时前
算法之双指针系列(一)
算法·leetcode
Pniubi20 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi21 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode2081~2100题目解析
java·leetcode
code2cat1 天前
【随笔】KV缓存卸载:逐层预取能藏住多少传输时间
人工智能·缓存·大语言模型
文丑颜不良啊1 天前
LeetCode2061~2080题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1941~1960题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2001~2020题目解析
java·leetcode