思想
基本思想是借助hash_map实现链表的快速查找,同时快速添加删除子节点。

C++实现
class LRUCache {
public:
LRUCache(int capacity) : cap(capacity) {
}
int get(int key) {
if (map.find(key) == map.end()) return -1;
auto key_value = *map[key];
cache.erase(map[key]);
cache.push_front(key_value);
map[key] = cache.begin();
return key_value.second;
}
void put(int key, int value) {
if (map.find(key) == map.end()) {
if (cache.size() == cap) {
map.erase(cache.back().first);
cache.pop_back();
}
}
else {
cache.erase(map[key]);
}
cache.push_front({key, value});
map[key] = cache.begin();
}
private:
int cap;
list<pair<int, int>> cache;
unordered_map<int, list<pair<int, int>>::iterator> map;
};
本文介绍了一种利用哈希映射和链表实现的LRU缓存数据结构,通过C++代码展示了如何高效地插入、删除和查找元素,遵循最近最少使用策略。
&spm=1001.2101.3001.5002&articleId=115421592&d=1&t=3&u=34cc976a4f0e47d9ab60a3b4bb6cbe1e)
389

被折叠的 条评论
为什么被折叠?



