2021年3月2日 周二 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
本文目录
1. 题目简介
2. 题解(链表+哈希表)
分析 LRU 的操作,要让 put 和 get 方法的时间复杂度为 O(1)
,可以总结出 cache 这个数据结构必要的条件:查找快,插入快,删除快,有顺序之分。所以考虑链表(插入快,删除快,有顺序之分) + 哈希表(查找快)。
class LRUCache {
private:
int cap;
list<pair<int,int>> cache;
// 注意:第二个元素为迭代器类型
unordered_map<int,list<pair<int,int>>::iterator> ump;
public:
LRUCache(int capacity):cap(capacity) {
}
int get(int key) {
if(ump.find(key)==ump.end()) return -1;
// 如果存在,先删除,然后添加到list的头部
pair<int,int> p = *ump[key];
cache.erase(ump[key]);
cache.push_front(p);
ump[key] = cache.begin();
return p.second;
}
void put(int key, int value) {
// 如果存在,先删除
if(ump.find(key)==ump.end()){
if(cache.size()==cap){
ump.erase(cache.back().first);
cache.pop_back();
}
}
else{
cache.erase(ump[key]);
}
// 保证list里没有{key,value},然后添加到list的头部
cache.push_front(make_pair(key,value));
ump[key] = cache.begin();
}
};
参考文献
https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he-shi-xian-by-labuladong/