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)
};
相关推荐
一拳一个呆瓜7 小时前
【STL】文件系统导航
c++·stl
All for pursuit.7 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
栈帧之外8 小时前
【C++】STL之set
开发语言·c++
zhanghaha13149 小时前
C++构造函数的一些其他应用(逐词逐句保姆讲解)
c++
jimy110 小时前
c++的 Type Traits (二、更详细版本)
开发语言·c++
半杯咖啡半行码12 小时前
C++11核心特性详解:从C++11到C++20 的现代C++指南
开发语言·c++
All for pursuit.13 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
C++ 老炮儿的技术栈14 小时前
std::atomic 是什么
linux·c语言·网络·c++·visual studio
All for pursuit.15 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
重生之小比特15 小时前
【算法拾光】双指针|移动零 + 复写零
数据结构·c++·算法