【力扣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);
 */
相关推荐
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll2 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐2 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶2 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
知我Deja_Vu2 天前
redisCommonHelper.generateCode(“GROUP“),Redis 生成码方法
数据库·redis·缓存
im_AMBER2 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了2 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333332 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录2 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode