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)
};
相关推荐
zh路西法1 小时前
【3D SLAM源码解读系列】(二)Small_gicp——5 个积木搭出最优点云配准
c++·pcl·icp·fastgicp·smallgicp·gicp
fpcc3 小时前
ubuntu26环境下的开发环境安装处理
c++·并行编程
charlie1145141914 小时前
Cinux · 第一次跳进 Ring 3:用户态与特权隔离
开发语言·c++·操作系统·开源项目
别动我齐刘海5 小时前
机器学习基础2——C++、OpenCV、点云、Open3D
c++·人工智能·opencv·机器学习·计算机视觉·机器人·ros2
躺不平的理查德5 小时前
Windows C++ 第三方库使用流程备忘录--OpenCV
开发语言·c++
余额瞒着我当琳5 小时前
C++STL容器string--迭代器,string的接口,string的遍历,访问方式
c++
郭涤生5 小时前
rootfs 详解与裁剪优化记录
linux·c++·bsp
MC皮蛋侠客5 小时前
TDengine C++ 系列(6):高性能写入——参数绑定、批量与 Schemaless
c++·php·tdengine
小小龙学IT6 小时前
C++ std::vector 底层实现深度解析:内存布局、扩容策略、移动语义与迭代器失效
开发语言·c++·算法
noipp6 小时前
推荐题目:洛谷 P16689 出征
java·开发语言·数据结构·c++·算法·洛谷·luogu