146.LRU缓存




双向链表+哈希表

cpp 复制代码
class LRUCache {
public:
    //1、定义双向链表结构、容量、哈希表等LRU数据成员
    struct Node{
        int key,value;
        Node *left,*right;
        Node(int _key,int _value):key(_key),value(_value),left(NULL),right(NULL){}
    }*L,*R;

    int n;
    unordered_map<int,Node*> ump;
    
    //2、初始化LRU缓冲,容量为capacity
    LRUCache(int capacity) {
        n=capacity;
        //L、R的分配内存及初始化
        L=new Node(-1,-1);
        R=new Node(-1,-1);
        L->right=R;
        R->left=L; 
    }
    
    //3、定义insert、remove操作
    void remove(Node *p){
        p->left->right=p->right;
        p->right->left=p->left;
    }

    //链表左侧为活跃节点,insert位置
    void insert(Node* p){
        L->right->left=p;
        p->right=L->right;
        p->left=L;
        L->right=p;
    }

    int get(int key) {
        if(ump.count(key)==0) return -1;
        Node *p=ump[key];
        remove(p);
        insert(p);
        return p->value;
    }
    
    void put(int key, int value) {
        if(ump.find(key)!=ump.end()){
            Node* p=ump[key];
            remove(p);
            insert(p);
            p->value=value;
        }else{
            if(ump.size()==n){
                Node *tmp=R->left;
                ump.erase(tmp->key);
                remove(tmp);
                delete tmp;
            }
            Node *p=new Node(key,value);
            insert(p);
            ump[key]=p;
        }
    }
};
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
-Xie-2 天前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
七夜zippoe2 天前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
weixin_456904272 天前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
MarkHard1233 天前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
心想事成的幸运大王3 天前
Redis的过期策略
数据库·redis·缓存
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步