题目描述:
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
class LRUCache {
public:
list<pair<int,int>> cache;
unordered_map<int,list<pair<int,int>>::iterator> record;
int size;
LRUCache(int capacity)
{
size = capacity;
}
int get(int key)
{
auto it = record.find(key);
if(it == record.end())
return -1;
else
{
list<pair<int,int>>::iterator temp = (*it).second;
int val = (*temp).second;
cache.erase(temp);
record.erase(it);
cache.push_front(make_pair(key,val));
record[key] = cache.begin();
return val;
}
}
void put(int key, int value)
{
auto it = record.find(key);
if(it == record.end())
{
if(cache.size() == size)
{
auto temp = cache.back();
int k = temp.first;
auto it = record.find(k);
record.erase(it);
cache.pop_back();
}
cache.push_front(make_pair(key,value));
record[key] = cache.begin();
}
else
{
list<pair<int,int>>::iterator temp = (*it).second;
cache.erase(temp);
record.erase(it);
cache.push_front(make_pair(key,value));
record[key] = cache.begin();
}
}
};
解题思路:
用一个双向链表存储pair<int,int>,用一个unordered_map<int,list<int,int>::iterator>存储key对应的pair再链表中的位置。
执行查找操作时,先从哈希表中找该key对应的位置,然后要更新这对pair对应的位置,list 和 哈希表中的位置都要更新,要将它放在list的最前边。
执行插入操作时,需要查看哈希表中有没有这个元素,如果没有,则要执行插入操作,首先要看表是否满了,若是,则要删除list最后的元素,以及再哈希表中的位置,然后再插入。若哈希表中含有这个元素,那么直接更新这个pair的位置即可。