您的位置:首页 >Python 实现 LRU 缓存经典面试题
发布于2026-02-28 阅读(0)
扫一扫,手机访问

Python 实现 LRU 缓存,核心在于 O(1) 时间复杂度完成 get 和 put 操作,同时自动淘汰最久未使用的项。标准解法是用 OrderedDict(Python 3.7+ 中普通 dict 也保持插入顺序,但 OrderedDict 提供了 move_to_end() 这一关键能力)。
OrderedDict 支持在 O(1) 时间内把某个 key 移动到末尾(move_to_end(key, last=True)),这正好对应“访问即更新为最近使用”。普通 dict 虽有序,但没有内置方法高效完成这一操作;手动删再插会多一次哈希查找和重建节点,逻辑冗余且易出错。
class LRUCache:
def init(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacityfrom collections import OrderedDict
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key) # 标记为最近使用
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False) # 删除最久未使用的(开头)</code></pre></font></p>面试中容易被追问的点
threading.Lock)或改用 functools.lru_cache(仅适用于函数级缓存)popitem 在空 dict 会报错,但容量为 0 时 put 后 len=1 > 0,会触发 pop,此时 OrderedDict 非空,安全
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9