【力扣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);
 */
相关推荐
人道领域几秒前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode
填满你的记忆14 分钟前
10万QPS下,Redis缓存如何避免雪崩?
数据库·redis·缓存
小欣加油39 分钟前
leetcode121买卖股票的最佳时机
数据结构·c++·算法·leetcode·职场和发展
10WTW0143 分钟前
QQ本地缓存机制初步探寻
缓存·视频·md5
2601_961194022 小时前
考研专业课在哪里参加考试|考点|流程|资料已整理
linux·考研·ubuntu·缓存·centos·负载均衡
闪电悠米2 小时前
黑马点评-Redis 消息队列-01_why_redis_mq
java·数据库·spring boot·redis·缓存·junit·消息队列
IT策士2 小时前
Redis 从入门到精通:初识 Redis
数据库·redis·缓存
IT策士2 小时前
Redis 从入门到精通:数据结构Hash 与 List
数据结构·redis·哈希算法
开源Z2 小时前
LeetCode 238 · 除自身以外数组的乘积:左右两遍扫描,不用除法
算法·leetcode
8Qi82 小时前
LeetCode 5:最长回文子串(Longest Palindromic Substring)—— 题解
算法·leetcode·职场和发展·动态规划