146. LRU 缓存

unordered_map+list 实现

此题需要先了解,LRU的实现原理,即当缓存池已满时,淘汰最近最久未使用的元素,并将新元素加入到缓存

过程题目中给出;

代码如下:

class LRUCache {
public:
    // 使用hash表
    unordered_map<int,int> mp;   // 作为存储数据的载体
    list<int> l; // 作为记录最近最少未使用的列表
    int size=0;   // 缓存池长度
    LRUCache(int capacity) {
        size = capacity;
    }
    int get(int key) {
        // 更新使用列表l
        auto it = mp.find(key);
        if(it==mp.end()){
            return -1;
        }
        update_l(key);
        return mp[key];
    }
    /**
    加入数据的时候,首先考虑以下几点
    1. 缓存池是否已满,如果已满淘汰最近最少未使用的算法(链表末尾数据,mp中置为-1,非物理删除),如果未满则直接加入
    2. 如果未满,加入缓存池(mp[])
    */
    void put(int key, int value) {
        // 查看是否存在与缓存池中,如果存在,则更新value
        if(is_exist(key,mp)!=-1){
            mp[key] = value;
            // 更新list
            update_l(key);
            return;
        }
        // 查看缓存池是否已满,如果已满则进行LRU算法
        if(l.size()>=size){
            
            // 不存在的情况,实行LRU算法,淘汰链表中最后一个,将新值加入到链表头部
            int k = l.back(); 
            mp.erase(k); // 删除尾部数据
            l.pop_back();
            l.push_front(key);
            mp[key] = value;
            return;
        }
        // 未满,直接加入缓存池
        mp[key] = value;
        l.push_front(key);
    }
    // 检查是否存在于缓存池中
    int is_exist(int key,unordered_map<int,int>& mp){
        auto it = mp.find(key);
        if(it!=mp.end()){
            return mp[key];
        }
        return -1;
    }
    // 更新链表
    void update_l(int key){
        auto it = find(l.begin(),l.end(),key);
        if(it!=l.end()){
            l.erase(it);
            l.push_front(key);
        }
    }
};

/**
 * 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);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值