面试150 LRU缓存

思路

这里我们使用collections中的OrderedDict去维护。因为它提供了一种有序的字典数据结构,它对比普通字典,OrderedDict会严格按照键值对的顺序插入顺序存储的书,即使在插入后修改已有的键,顺序也不会改变。并且它提供的over_to_end方法,可将指定键移动到字典的末尾(last=True)或开头(last=False),支持popitem(last=True)方法,按顺序弹出最后一个(last=True)或第一个(last=False)键值对

python 复制代码
class LRUCache:

    def __init__(self, capacity: int):
        self.cache=OrderedDict()
        self.capacity=capacity

    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)

# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
特性 OrderedDict Python 3.7+ 普通字典 (dict)
插入顺序保留
顺序敏感比较
move_to_end() 支持 不支持
内存占用 更高(维护双向链表) 更低
性能 略低(因额外维护顺序) 更高
相关推荐
Kuo-Teng39 分钟前
LeetCode 142: Linked List Cycle II
java·算法·leetcode·链表·职场和发展
早上好啊! 树哥1 小时前
安卓开发:清除缓存并重启,删除指定路径下的文件缓存
android·缓存
z***3351 小时前
redis清理缓存
数据库·redis·缓存
麦兜*12 小时前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
成为你的宁宁13 小时前
【Redis 从入门到实战:详细讲解 Redis 安装配置、RDB/AOF 数据持久化方案、一主两从同步部署,深入剖析哨兵模式工作原理与哨兵模式高可用全攻略】
数据库·redis·缓存
ifeng091813 小时前
HarmonyOS网络请求优化实战:智能缓存、批量处理与竞态处理
网络·缓存·harmonyos
5***o50013 小时前
前端构建工具缓存清理,解决依赖问题
前端·缓存
一叶飘零_sweeeet17 小时前
2025 年 Redis 面试天花板
redis·缓存·面试
d***93518 小时前
Redis五种用途
数据库·redis·缓存