LRU/LFU 发表于 2022-05-19 | 分类于 数据结构 , LRU/LFU , LRU/LFU | LRU/LFU 146.LRU缓存123456789101112131415161718192021222324252627282930313233343536373839404142434445class LRUCache {public: LRUCache(int capacity) { cap = capacity; } int get(int key) { auto it = mp.find(key); //返回迭代器 //如果 key 不存在则返回 -1 if(it==mp.end()) return -1; //提升为最近使用的,将该结点移动到链表头 lst.splice(lst.begin(), lst, it->second); return mp[key]->second; } void put(int key, int value) { if(mp.find(key)==mp.end()){ //key不存在 if(lst.size()==cap){ //删除最久未使用的元素 mp.erase(lst.back().first); lst.pop_back(); } }else{ //key已存在,抹去 lst.erase(mp[key]); } //插入{key, value} lst.push_front({key, value}); //添加mp中 key 到 list迭代器的映射 mp[key] = lst.begin(); }private: //缓存容量 int cap; //双向链表,存储 key-value list<pair<int, int>> lst; //哈希表,存储 key-(key, value) 迭代器 unordered_map<int, list<pair<int, int>>::iterator> mp;};/** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */ -------------本文结束 感谢阅读------------- 本文作者: HReina 本文链接: http://hreina.com/2022/05/19/LRU_LFU/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!