LRU cache的简单实现
来源:互联网 发布:下载xlsx软件 编辑:程序博客网 时间:2024/05/21 10:29
从昨天想起这个东西,中午写好了,但是leetcode上还木有ac:
就是用双链表存储,同时用一个map存储链表:
LRUCache(int capacity):maxSize(capacity), curSize(0){pHead = new LinkedList(-1, -1);pHead->pre = pHead;pHead->next = pHead;}~LRUCache(){for (MapList::iterator iter = mapList.begin(); iter != mapList.end(); ++iter){delete iter->second;}delete pHead;}void set(int key,int val){MapList::iterator iter = mapList.find(key);if (mapList.end() == iter){if (maxSize == curSize){LinkedList* pToDel = pHead->pre;pHead->pre = pToDel->pre;pToDel->pre->next = pHead;mapList.erase(pToDel->key);pToDel->key = key;pToDel->val = val;mapList[key] = pToDel; }else{LinkedList* pCurList = new LinkedList(key, val);pHead->next->pre = pCurList;pCurList->next = pHead->next;pHead->next = pCurList;pCurList->pre = pHead;mapList[key] = pCurList;++curSize;}}else{LinkedList* pCurList = iter->second;pCurList->pre->next = pCurList->next;pCurList->next->pre = pCurList->pre;pCurList->next = pHead->next;pCurList->pre = pHead;pHead->next = pCurList;}}int get(int key){MapList::iterator iter = mapList.find(key);if (mapList.end() == iter){printf("can't find key:%d\n", key);return -1;}else{LinkedList* pCurList = iter->second;pCurList->pre->next = pCurList->next;pCurList->next->pre = pCurList->pre;pCurList->next = pHead->next;pCurList->pre = pHead;pHead->next = pCurList;}return (iter->second)->val;}private:struct LinkedList{int key;int val;LinkedList* pre;LinkedList* next;LinkedList(int key, int val):key(key), val(val), pre(NULL), next(NULL){}};const int maxSize;int curSize;LinkedList* pHead;typedef std::map<int, LinkedList*> MapList;MapList mapList;
这里实现的思路是set时超过了size就删掉最早插入的那个节点。
貌似木有用到get这个查询的用法,想了下还是保存查询的次数纪录,可以用位图的办法。下午吃饭的时候再写。
0 0
- LRU cache的简单实现
- LRU Cache的简单实现
- 简单LRU cache 实现
- 用LinkedHashMap实现的简单LRU Cache
- LRU Cache的简单c++实现
- LRU cache的一个简单实现
- java实现简单的LRU Cache
- LRU cache的实现
- LRU Cache的实现
- LRU Cache的实现
- LRU Cache的实现
- 简单LRU算法实现的Cache(C++)
- 简单LRU算法实现的Cache(C++)
- 简单LRU算法实现的Cache(C++)
- 简单LRU算法实现的Cache(C++)
- LRU的cache的实现
- LRU Cache的一种实现
- LRU cache的另一种实现
- LINUX下的REALVNC部署方法(全)
- Unity 利用Quaternion.LookRotation API 将旋转矩阵转换成四元数
- vector<IplImage*>类型时push_back问题
- redhat 6设置CentOS的yum源
- Android library projects cannot be launched 问题解决方法
- LRU cache的简单实现
- Hibernate中inverse属性与cascade属性
- 解决jQuery $.getJSON() 传递参数中文乱码问题
- HashMap / Hashtable / LinkedHashMap / TreeMap的区别
- c++11学习笔记之auto
- 自适应波束形成(二)——时域窄带LCMV波束形成器
- Java中的线程池
- android相对布局RelativeLayout介绍
- 装配中部件做布尔操作