LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 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
思路:
- 首先要想好用哪几个数据结构。这里我们采用3个数据类型 :int 记录最大容量、list<pair<int,int>>双向链表记录<键,值>,unordered_map<int, list<pair<int,int>>::iterator> 记录每个键对应的<键,值>在双向链表中的位置。
- 我们在获取数据时,首先使用unordered_map判断有没有该数据。其次,通过unordered_map的值,获取链表位置,获得键对应的值。最后,更新该<键,值>到list的头部,因为只要使用了,就得更新到最近的位置。
- 在插入的时候,首先unordered_map判断有没有该数据,有则更新键值,并且更新<键,值>在list中的位置。若没有,则使用 int 判断链表容量是不是满了,若果满了,则删除链表最后一个元素,还要删除unordered_map中的索引。再更新list和unordered_map。
代码:
class LRUCache {
public:
int cap;
list<pair<int,int>> li;
unordered_map<int, list<pair<int,int>>::iterator > up;
LRUCache(int capacity) {
cap=capacity;
}
int get(int key) {
if(up.find(key)!=up.end())
{
auto tmp= *up[key]; //获取该元素值
li.erase(up[key]); //在链表中去除该元素,erase参数为迭代器
li.push_front(tmp); //将该元素放在链表头部
up[key]=li.begin(); //重新索引该元素
return tmp.second; //返回值
}
return -1;
}
void put(int key, int value) {
if(up.find(key)!=up.end())
{
auto tmp=*up[key];
li.erase(up[key]);
tmp.second=value;
li.push_front(tmp);
up[key]=li.begin();
}else{
if(up.size()>=cap)
{
auto tmp=li.back();
li.pop_back();
up.erase(tmp.first);
}
li.push_front(make_pair(key,value));
up[key]=li.begin();
}
}
};
结果:
参考链接:
[1] 二次元憨批:leetcode_146. LRU缓存机制