题目
实现一个固定正容量的 LRUCache 类。get(key) 在命中时返回缓存值,并把该键标记为最近使用;未命中时返回 -1。put(key, value) 插入或更新键值,并把该键标记为最近使用;当条目数超过容量时,淘汰最久未使用的键。要求两个操作的平均时间复杂度都是 O(1)。
- 输入:先用一个正整数构造缓存,然后依次执行若干 get 与 put 操作。
- 输出:按调用顺序收集所有 get 的返回值,未命中记为 -1。
解题思路
OrderedDict 同时维护哈希索引和插入顺序,并提供 move_to_end 与 popitem(last=False)。get 命中后先把键移到末尾,再返回对应值;put 遇到已有键时也要先移到末尾,然后更新值,最后在长度超过容量时从头部弹出最旧条目。需要注意,直接给 OrderedDict 中已存在的键重新赋值不会改变它的位置,因此显式 move_to_end 不能省略。
每次操作只涉及常数个字典节点和链表指针,时间复杂度 O(1),空间复杂度 O(capacity)。如果手写双向链表加哈希表,复杂度相同,但代码量明显更大。
参考实现要点
- 构造函数校验 capacity >= 1,非法值抛出 ValueError。
- get 先判断键是否存在,存在时调用 move_to_end(key),再返回 _data[key]。
- put 若键已存在,先 move_to_end(key),再赋值,避免旧键位置不变。
- 赋值后检查 len(_data) > capacity,满足时执行 popitem(last=False) 淘汰头部。
- 返回 -1 只用于未命中,缓存中真实存储的 None 或 0 不应被误判。
常见错误
- 更新已有键时忘记刷新顺序,导致刚访问的键被优先淘汰。
- 先淘汰再插入,容量为 1 时可能把刚写入的条目删掉,应插入后再判断。
- 用 popitem() 默认参数从尾部弹出,结果淘汰了最近使用的键。
- 把 get 的未命中值与存储值混为一谈,命中值为 -1 时无法区分。
验证方式
用容量 1 测试插入第二个键后第一个键是否失效;用容量 2 执行 get(1)、put(3,3),确认被淘汰的是键 2。再覆盖重复 put、更新已有键、空缓存 get、以及容量为 1 的连续写入。运行脚本应依次打印 1、-1、3、1。
代码示例
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
if capacity < 1:
raise ValueError("capacity must be positive")
self.capacity = capacity
self._data = OrderedDict()
def get(self, key):
if key not in self._data:
return -1
self._data.move_to_end(key)
return self._data[key]
def put(self, key, value) -> None:
if key in self._data:
self._data.move_to_end(key)
self._data[key] = value
if len(self._data) > self.capacity:
self._data.popitem(last=False)
if __name__ == "__main__":
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1))
cache.put(3, 3)
print(cache.get(2))
print(cache.get(3))
print(cache.get(1))