解题思路:
使用一个双向链表存储最常使用的key value对,最近使用的元素放在链表的表头,链表中最后一个元素是使用频率最低的元素。同时,使用一个map来记录对应的<key,<key, value>>,用于查找现在的缓存中是否有key及其value。
class LRUCache {
public:
int n;
list<pair<int, int>> lis;
map<int, list<pair<int, int>>::iterator> mp;
LRUCache(int capacity) {
n = capacity; //初始化缓存大小
}
int get(int key) {
int ret = -1;
if(mp.find(key) != mp.end()){ // 缓存中已经存在key
auto iter = mp[key];
ret = iter->second;
lis.erase(iter); //在链表中删除这个key和value
lis.push_front(make_pair(key, ret)); //再把这个key和value放在链表的表头
mp[key] = lis.begin(); //同时,要更新map中key所指向链表的位置
}
return ret; //返回value值
}
void put(int key, int value) {
auto iter = mp.find(key); //看看map中是否有这个key
if(iter != mp.end()){ //如果有,则更新这个key在链表中的顺序,需先删除,然后再push_front在表头
lis.erase(iter->second);
}
else if(lis.size() < n){ //如果链表中的元素个数小于可缓存数
}
else{ //list中没有key,且已超过n个
int key = lis.back().first;
lis.pop_back(); //擦除最少使用的key value对
mp.erase(key); //同时擦除map中对应的元素
}
lis.push_front(make_pair(key, value));
mp[key] = lis.begin();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/