LRU Cache 最近最少使用

146. LRU 缓存 - 力扣(LeetCode)

链表:增删改O(1)

哈希表:增删改查O(1)

模板:

cpp 复制代码
class LRUCache 
{
public:
    LRUCache(int capacity) 
        :_capacity(capacity)
    {}
    
    int get(int key) 
    {
        auto iter = _hashmap.find(key);
        if(iter != _hashmap.end())
        {
            auto listIter = iter->second;
            pair<int,int> tmp = *listIter;
            
            _list.erase(listIter);
            
            _list.push_front(tmp);
            _hashmap[key] = _list.begin();

            return tmp.second;
        }
        return -1;
    }
    
    void put(int key, int value) 
    {
        auto iter = _hashmap.find(key);
        //不存在
        if(iter == _hashmap.end())
        {
            //LRU淘汰
            if(_capacity <= _list.size())
            {
                _hashmap.erase(_list.back().first);
                _list.pop_back();
            }
            _list.push_front(make_pair(key,value));
            _hashmap[key] = _list.begin();
        }
        else
        {
            auto listIter = iter->second;
            pair<int,int> tmp = *listIter;
            tmp.second = value;

            _list.erase(listIter);
            
            _list.push_front(tmp);
            _hashmap[key] = _list.begin();
        }
    }
private:
    size_t _capacity;
    list<pair<int,int>> _list; //使用list--增删改O(1)
    unordered_map<int, list<pair<int,int>>::iterator> _hashmap; //使用unordered_map--增删查改O(1)
};
相关推荐
坚定学代码2 分钟前
qt c++ 局域网聊天小工具
c++·qt·个人开发
晓纪同学7 分钟前
EffctiveC++_01第一章
java·开发语言·c++
2401_8463416512 分钟前
C++动态链接库开发
开发语言·c++·算法
lisanndesu19 分钟前
第十五届蓝桥杯 C++A组
c++·蓝桥杯
-Excalibur-1 小时前
IP数据包在计算机网络传输的全过程
java·网络·c++·笔记·python·网络协议·智能路由器
历程里程碑1 小时前
41 .UDP -3 群聊功能实现:线程池助力多客户端通信
linux·开发语言·网络·数据结构·c++·网络协议·udp
山栀shanzhi1 小时前
【FFmpeg】是什么是未压缩的裸流?
c++·ffmpeg
不染尘.1 小时前
排序算法详解1
开发语言·数据结构·c++·算法·排序算法
啊我不会诶1 小时前
25CCPC东北邀请赛vp补题
c++·算法