标签:
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;
};
标签:
原文地址:http://www.cnblogs.com/wuxiangli/p/5638152.html