设计LRU缓存结构_牛客题霸_牛客网 (nowcoder.com)
LRU缓存结构,是一种常见得缓存替换策略,通过保留最近使用得数据,淘汰长时间没被使用得数据,以提高缓存得命中率和性能。
1. Solution(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
2. get(key):如果关键字 key 存在于缓存中,则返回key对应的value值,否则返回 -1 。
3. set(key, value):将记录(key, value)插入该结构,如果关键字 key 已经存在,则变更其数据值 value,如果不存在,则向缓存中插入该组 key-value ,如果key-value的数量超过capacity,弹出最久未使用的key-value
/*
使用哈希表和双向链表来实现LRU算法,哈希表用于快速查找数据是否存在于缓存中,双向链表用于维护数据的访问顺序;
*/
class Solution {
list<pair<int, int>> dlist;//双向链表
unordered_map<int, list<pair<int, int>>::iterator> map;
int cap;
//用链表存,链表头部是最近使用的,尾部是最后使用的,如果要删去,就直接把尾部删去就好
public:
Solution(int capacity){
cap=capacity;
}
//key就变得最常用了
int get(int key) {
if(map.count(key))
{
//把这个放在头部,所以需要个tmp存着,然后删掉这个位置,再放到头部
auto tmp=*map[key];
dlist.erase(map[key]);
//map.erase(key);
dlist.push_front(tmp);//把它放在最前面
map[key]=dlist.begin();
//return tmp.second;
return dlist.front().second;
}
return -1;
}
void set(int key, int value){
if(map.count(key))//如果存在
{
dlist.erase(map[key]);//放在头部
//map.erase(key);
}
else if(cap==dlist.size())
{
//先删掉末尾的
auto tmp=dlist.back();
map.erase(tmp.first);
dlist.pop_back();
}
dlist.push_front(pair<int, int>(key, value));
map[key]=dlist.begin();//第一个迭代器
}
};