从昨天想起这个东西,中午写好了,但是leetcode上还木有ac:
就是用双链表存储,同时用一个map存储链表:
#include <iostream>
#include <map>
namespace std
{
using namespace __gnu_cxx;
}
class LRUCache{
public:
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;
}
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* pList;
LinkedList* pHead;
typedef std::map<int, LinkedList*> MapList;
MapList mapList;
};
int main(){
LRUCache m(5);
m.set(2,1);
m.set(3,2);
printf("%d\n", m.get(3));
printf("%d\n", m.get(2));
m.set(4,3);
printf("%d\n", m.get(2));
printf("%d\n", m.get(3));
printf("%d\n", m.get(4));
}这里实现的思路是set时超过了size就删掉最早插入的那个节点。
貌似木有用到get这个查询的用法,想了下还是保存查询的次数纪录,可以用位图的办法。下午吃饭的时候再写。
原文:http://blog.csdn.net/boyxiaolong/article/details/22171825