leetcode 146. LRU Cache
来源:互联网 发布:淘宝客服自动分流不均 编辑:程序博客网 时间:2024/06/08 20:08
题意:实现LRU(最近最久未用),包括get和set操作。
//使用一个双向链表存储数据(地址和内容),数据的顺序表示了它们被访问的时间顺序,越靠后访问时间越早//使用Map存储地址(key)对应的链表中数据的地址,加快数据的查找速度//get操作:只需向Map中查找是否有对应项即可,存在则将双向链表中的数据删除,并在链表前端重新插入//set操作:先在Map中查找是否有对应项,如果有,则将链表中的项直接删除再插入,如果没有直接向链表头插入数据//插入完成需要检测元素个数是否超过了缓存容量,超过了则将链表尾部删除class LRUCache {public: LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { map<int, list<node>::iterator>::iterator it = memMap.find(key); int retVal = -1; if(it != memMap.end()) { node nt = *(it->second); retVal = nt.value; memList.erase(it->second); memList.push_front(nt); memMap[key] = memList.begin(); } return retVal; } void put(int key, int val) { map<int, list<node>::iterator>::iterator it = memMap.find(key); node nt(key, val); if(it != memMap.end()) { memList.erase(it->second); } memList.push_front(nt); memMap[key] = memList.begin(); if(memList.size()>this->capacity) { int dkey = memList.back().address; memList.pop_back(); memMap.erase(dkey); } }private: struct node { int address; int value; node(int add, int val) { address = add; value = val; } }; unsigned int capacity; list<node> memList; map<int, list<node>::iterator> memMap;};
阅读全文
0 0
- LeetCode 146. LRU Cache
- [leetcode] 146.LRU Cache
- leetcode 146. LRU Cache
- Leetcode 146. LRU Cache
- Leetcode - 146. LRU Cache
- Leetcode 146. LRU Cache
- [leetcode] 146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode 146. LRU Cache
- LeetCode-146. LRU Cache
- LeetCode 146. LRU Cache
- LeetCode 146. LRU Cache
- Leetcode 146. LRU Cache
- [LeetCode] 146. LRU Cache
- leetcode 146.LRU Cache
- [LeetCode]146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode 146. LRU Cache
- Leetcode Symmetric Tree
- 【知识库】--git删除远程分支(242)
- cocos2dx导入已有的项目
- 【Linux】中的线程死锁详解
- SSL1333 地鼠的困境(最大匹配)
- leetcode 146. LRU Cache
- 【Java设计模式】- 观察者模式
- android 5.0+录屏功能实现
- linux下使用opencv接口函数对图像进行光滑处理
- 常用证书操作函数
- maven多模块
- android 绘制自定义控件
- 《深入理解java虚拟机》学习笔记3——垃圾回收算法
- 入门经典_Chap06_例题[一]:队列,栈,链表的数组实现