行业知识
[力扣 Hot100]Day35 LRU 缓存
2026-10-20 08:36:57
来源:互联网转载
题目描述
请��设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
出处
思路
写了两个版本都超时,单向链表和迭代器的查找都太慢,需要用哈希表。
代码
class LRUCache {private: int len; list lru; unordered_map map;public: LRUCache(int capacity) { len=capacity; } int get(int key) { if (map.find(key) == map.end()) return -1; pair key_value = *map[key]; lru.erase(map[key]); lru.push_front(key_value); map[key] = lru.begin(); return key_value.second; } void put(int key, int value) { if (map.find(key) == map.end()) { if (lru.size() == len) { map.erase(lru.back().first); lru.pop_back(); } } else { lru.erase(map[key]); } lru.push_front({key, value}); map[key] = lru.begin(); }};
上一篇:怎么攻击服务器拿到源代码?
下一篇:rust历史服务器怎么删除?