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)
};
相关推荐
郝学胜-神的一滴5 小时前
深入解析Linux下的`lseek`函数:文件定位与操作的艺术
linux·运维·服务器·开发语言·c++·软件工程
仰泳的熊猫5 小时前
LeetCode:889. 根据前序和后序遍历构造二叉树
数据结构·c++·算法
小欣加油6 小时前
leetcode 329 矩阵中的最长递增路径
c++·算法·leetcode·矩阵·深度优先·剪枝
_给我学起来6 小时前
字符数组和字符串
c++
骁的小小站6 小时前
Learn C the Hardway学习笔记和拓展知识(一)
c语言·开发语言·c++·经验分享·笔记·学习·bash
仰泳的熊猫7 小时前
LeetCode:700. 二叉搜索树中的搜索
数据结构·c++·算法·leetcode
楼田莉子7 小时前
C++学习:异常及其处理
开发语言·c++·学习·visual studio
杰 .8 小时前
C++ Hash
数据结构·c++·哈希算法
GHL2842710908 小时前
用PDH库获取CPU使用率(源码)
c++