问题描述
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
- 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
- 写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
[
1
]
^{[1]}
[1]
解题报告
哈希表+ 双向链表
哈希表
能够实现
O
(
1
)
O(1)
O(1) 的时间复杂度内获取或者插入一个元素,但是当 哈希表
满的时候,无法在
O
(
1
)
O(1)
O(1) 的时间内找到 最久未使用的数据值
。
解决这一问题的方法是再加入一个双向链表。
get(key)
元素时,首先从哈希表获取指向value
的指针,然后将指向value
的指针调整到链表头。put(key, value)
元素时,
- 如果哈希表中不存在该key
且当前容器大小未超出容器容量,那么直接在链表头插入该key
对应的value
,并将key,[指针]
存到哈希表中。
- 如果哈希表中不存在该key
且当前容器大小超出容器容量,那么首先需要将最久未使用的数据
先删去【该元素即为链表尾部节点】。然后重新执行put
操作。
- 如果 链表中已经存在 直接取到元素(mp[key]) 更新元素中的val(mp[key]->val = value)然后调整到头部head 即可 [ 2 ] ^{[2]} [2]。
实验代码
struct listNode{
int key;
int val;
listNode *next;
listNode *prev;
listNode(int _key,int _val):key(_key),val(_val),next(nullptr),prev(nullptr){}
};
class LRUCache {
public:
unordered_map <int,listNode *> mp;
listNode *head;
listNode *tail;
int size_l;
int cap;
LRUCache(int capacity) {
cap = capacity;
size_l = 0;
head = new listNode(-1,-1);
tail = new listNode(-1,-1);
head->next = tail;
tail->prev = head;
}
int get(int key) {
if(mp.count(key) == 0){
return -1;
}
listNode *tmp =mp[key];
int val = tmp->val;
//调整tmp位置
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
//调整到表头位置
head->next->prev = tmp;
tmp->next = head->next;
tmp->prev = head;
head->next = tmp;
return val;
}
void put(int key, int value) {
//不存在,并且有容量
if(mp.count(key) == 0 && size_l < cap){
listNode *tmp = new listNode(key,value);
head->next->prev = tmp;
tmp->next = head->next ;
tmp->prev = head;
head->next = tmp;
size_l++;
mp[key] = tmp;
return ;
}
if(mp.count(key) == 0 && size_l>=cap){
//删除尾部节点
listNode *tmp = tail->prev;
tmp->prev->next = tail;
tail->prev = tmp->prev;
//清楚map数据 移除元素空间
mp.erase(tmp->key);
delete tmp;
size_l --;
//调用添加
put(key,value);
return;
}
//已经存在,需要更新
if(mp.count(key)==1){
listNode *tmp = mp[key];
//key 相同但是 val不一定相同
tmp->val = value;
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
head->next->prev = tmp;
tmp->next = head->next;
tmp->prev = head;
head->next = tmp;
return ;
}
}
};
/**
* 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);
*/
// 作者:xing-yuan-21
// 链接:https://leetcode-cn.com/problems/lru-cache/solution/146-lruhuan-cun-ji-zhi-mapshuang-xiang-dui-lie-shi/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
参考资料
[1] Leetcode 146. LRU缓存机制
[2] 题解区 星缘