题目描述
请你设计并实现一个满足 lru (最近最少使用) 缓存 约束的数据结构。
实现 lrucache
类:
lrucache(int capacity)
以 正整数 作为容量capacity
初始化 lru 缓存int get(int key)
如果关键字key
存在于缓存中,则返回关键字的值,否则返回-1
。void put(int key, int value)
如果关键字key
已经存在,则变更其数据值value
;如果不存在,则向缓存中插入该组key-value
。如果插入操作导致关键字数量超过capacity
,则应该 逐出 最久未使用的关键字。
函数 get
和 put
必须以 o(1)
的平均时间复杂度运行。
样例输入
示例:
输入 ["lrucache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] 输出 [null, null, null, 1, null, -1, null, -1, 3, 4] 解释 lrucache lrucache = new lrucache(2); lrucache.put(1, 1); // 缓存是 {1=1} lrucache.put(2, 2); // 缓存是 {1=1, 2=2} lrucache.get(1); // 返回 1 lrucache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} lrucache.get(2); // 返回 -1 (未找到) lrucache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} lrucache.get(1); // 返回 -1 (未找到) lrucache.get(3); // 返回 3 lrucache.get(4); // 返回 4
提示:
1 <= capacity <= 3000
0 <= key <= 10000
0 <= value <= 105
- 最多调用
2 * 105
次get
和put
题解
- 使用双链表模拟缓存。链表头部作为缓存入口(插入节点),用于保存最近刚被访问的页面;链表尾部作为缓存出口(删除节点),用于删除最近最久没有被访问的页面
- 为了便于链表节点的查找,需要定义一个哈希表,用于保存key和对应节点的关系
- get函数用于模拟cpu对缓存的访问,也就是对内存页的访问。
- 由lru算法原理可知,每访问一次缓存,如果能够命中该页面,则说明该页面刚刚被访问过,因此需要将该节点(页面)移动到链表头部
- put函数用于模拟向缓冲中插入页面。
- 每次向缓存中插入页面时,都需要首先检查该页面是否在缓存中
- 如果不在则直接将该页面插入到链表头部(因为该页面刚刚被访问过),同时判断此时缓冲中的大小是否已经超过容量,如果超过则需要从缓存中删除该节点(页面)
- 如果页面在缓存中,则直接将该页面放入链表头部
struct dlinknode
{
int _key,_val;
struct dlinknode* prev,*next;
};
class lrucache {
private:
unordered_map<int,dlinknode*> _mp;
dlinknode* head,*tail;
int _size;
int _capacity;
public:
lrucache(int capacity):_capacity(capacity),_size(0) {
head=new dlinknode(0);
tail=new dlinknode(0);
head->next=tail;
tail->prev=head;
}
int get(int key) {
auto it=_mp.find(key);
if(it==_mp.end())
{
return -1;
}else{
movehead(it->second);
return it->second->_val;
}
}
void put(int key, int value) {
auto it=_mp.find(key);
if(it==_mp.end())
{
dlinknode* e=new dlinknode(key,value);
addhead(e);
_size++;
_mp[key]=e;
if(_size>_capacity)
{
dlinknode* tmp=tail->prev;
removenode(tmp);
_mp.erase(tmp->_key);
delete tmp;
_size--;
}
}else{
it->second->_val=value;
movehead(it->second);
}
}
void removenode(dlinknode* node)
{
node->prev->next=node->next;
node->next->prev=node->prev;
}
void addhead(dlinknode* node)
{
node->prev=head;
node->next=head->next;
head->next->prev=node;
head->next=node;
}
void movehead(dlinknode* node)
{
removenode(node);
addhead(node);
}
};
/**
* 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);
*/
发表评论