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)
};
相关推荐
澈20741 分钟前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
A.A呐42 分钟前
【C++第二十九章】IO流
开发语言·c++
ambition202421 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
kebeiovo1 小时前
atomic原子操作实现无锁队列
服务器·c++
Yungoal1 小时前
常见 时间复杂度计算
c++·算法
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
Ricky_Theseus3 小时前
C++右值引用
java·开发语言·c++
吴梓穆3 小时前
UE5 c++ 常用方法
java·c++·ue5
云栖梦泽3 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
Morwit3 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展