LRU设计
list是双向链表,map保存key对应到list中的迭代器的位置,list保存<key,value>
class LRUCache { private: int c; map<int, list<pair<int, int>>::iterator> mymap; list<pair<int, int>> mylist; public: LRUCache(int capacity) { // do intialization if necessary c = capacity; } int get(int key) { // write your code here 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 put(int key, int value) { // write your code here if (mymap.count(key) == 0) { if (mymap.size() == c) { int tmpkey = mylist.back().first; mylist.pop_back(); mymap.erase(tmpkey); } mylist.push_front(pair<int, int>(key, value)); mymap[key] = mylist.begin(); } else { list<pair<int, int>>::iterator it = mymap[key]; mylist.erase(it); mylist.push_front(pair<int, int>(key, value)); mymap[key] = mylist.begin(); } } };