unordered_map+list 实现
此题需要先了解,LRU的实现原理,即当缓存池已满时,淘汰最近最久未使用的元素,并将新元素加入到缓存
过程题目中给出;
代码如下:
class LRUCache {
public:
// 使用hash表
unordered_map<int,int> mp; // 作为存储数据的载体
list<int> l; // 作为记录最近最少未使用的列表
int size=0; // 缓存池长度
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
// 更新使用列表l
auto it = mp.find(key);
if(it==mp.end()){
return -1;
}
update_l(key);
return mp[key];
}
/**
加入数据的时候,首先考虑以下几点
1. 缓存池是否已满,如果已满淘汰最近最少未使用的算法(链表末尾数据,mp中置为-1,非物理删除),如果未满则直接加入
2. 如果未满,加入缓存池(mp[])
*/
void put(int key, int value) {
// 查看是否存在与缓存池中,如果存在,则更新value
if(is_exist(key,mp)!=-1){
mp[key] = value;
// 更新list
update_l(key);
return;
}
// 查看缓存池是否已满,如果已满则进行LRU算法
if(l.size()>=size){
// 不存在的情况,实行LRU算法,淘汰链表中最后一个,将新值加入到链表头部
int k = l.back();
mp.erase(k); // 删除尾部数据
l.pop_back();
l.push_front(key);
mp[key] = value;
return;
}
// 未满,直接加入缓存池
mp[key] = value;
l.push_front(key);
}
// 检查是否存在于缓存池中
int is_exist(int key,unordered_map<int,int>& mp){
auto it = mp.find(key);
if(it!=mp.end()){
return mp[key];
}
return -1;
}
// 更新链表
void update_l(int key){
auto it = find(l.begin(),l.end(),key);
if(it!=l.end()){
l.erase(it);
l.push_front(key);
}
}
};
/**
* 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);
*/