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;
        }
    }
};
相关推荐
哦吼!2 小时前
数据结构—二叉树(二)
数据结构
汤姆大聪明3 小时前
Redis 持久化机制
数据库·redis·缓存
码农Cloudy.4 小时前
C语言<数据结构-链表>
c语言·数据结构·链表
lightqjx4 小时前
【数据结构】顺序表(sequential list)
c语言·开发语言·数据结构·算法
田野追逐星光5 小时前
堆的应用(讲解超详细)
数据结构
kk在加油6 小时前
Redis数据安全性分析
数据库·redis·缓存
谭林杰6 小时前
散链表基本操作讲解
数据结构·链表
yi.Ist6 小时前
数据结构 —— 栈(stack)在算法思维中的巧妙运用
开发语言·数据结构
祁思妙想7 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
橘颂TA7 小时前
【C++】红黑树的底层思想 and 大厂面试常问
数据结构·c++·算法·红黑树