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)
};
相关推荐
Escalating_xu24 分钟前
C++可变参数模板与引用折叠精讲
开发语言·c++
云泽80836 分钟前
Visual Studio 2026 新手保姆级教程:环境搭建、界面优化与编译器配置详解
开发语言·c++·c·开发工具·visual studio
fqbqrr2 小时前
2607d,C++细节比不上d
c++·d
^yi2 小时前
【C++】继承的那些事儿~
c++·继承·菱形继承·隐藏·final·继承原理·多继承的指针偏移
ShineWinsu3 小时前
对于Linux:模版方法类的解析以及socket、TcpSocket的封装
linux·c++·面试·socket·模板方法模式·封装·tcpsocket
hold?fish:palm4 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
啦啦啦啦啦zzzz5 小时前
算法:回溯算法
c++·算法·leetcode
Lzg_na6 小时前
订阅发布模块事例
c++
攻城狮Soar6 小时前
C++子类访问父类成员
c++·算法
郝学胜-神的一滴6 小时前
[简化版 GAMES 104] 现代游戏引擎 02:拆解现代游戏引擎5+1层级架构,吃透引擎底层核心逻辑
c++·unity·架构·游戏引擎·图形渲染·unreal engine·系统设计