码迷,mamicode.com
首页 > 其他好文 > 详细

LRU设计

时间:2016-07-03 17:08:20      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

list是双向链表,map保存key对应到list中的迭代器的位置,list保存<key,value>

class LRUCache{
public:
LRUCache(int capacity) {
c = capacity;
}

int get(int key) {
if (mymap.count(key)==0)
return -1;
list<pair<int, int>>::iterator it = mymap[key];
int val = it->second;
mylist.erase(it);
mylist.push_front(pair<int,int>(key,val));
mymap[key] = mylist.begin();
return val;
}

void set(int key, int value) {
if (mymap.count(key) != 0)
{
list<pair<int, int>>::iterator it = mymap[key];
mylist.erase(it);
mylist.push_front(pair<int, int>(key, value));
mymap[key] = mylist.begin();
}
else
{
if (mymap.size() == c)
{
mymap.erase(mylist.back().first);
mylist.pop_back();
}
mylist.push_front(pair<int, int>(key, value));
mymap[key] = mylist.begin();
}
}
private:
list<pair<int, int>> mylist;
map<int, list<pair<int,int>>::iterator> mymap;
int c;

};

LRU设计

标签:

原文地址:http://www.cnblogs.com/wuxiangli/p/5638152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!