Coding中等
LC146 LRU 缓存机制
哈希 + 双向链表 → get/put 都 O(1);
简要回答
哈希 + 双向链表 → get/put 都 O(1);Python OrderedDict.move_{to}_{end}` 一行解决。
标准答案
考察点:哈希 + 双向链表 → get/put 都 O(1);Python OrderedDict.move_{to}_{end}` 一行解决。
实现:
from collections import OrderedDictclass LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = OrderedDict() # 内置双向链表,有序
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key) # 访问后移到尾(最近用)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.cap:
# popitem(last=False) 弹最旧;同步从哈希删(OrderedDict 一并删)
self.cache.popitem(last=False)
常见错误
- 用单链表无法 O(1) 删中间节点
- 超容量后只删链表忘删哈希
get已存在 key 忘move_{to}_{end}。