面试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() 支持 不支持
内存占用 更高(维护双向链表) 更低
性能 略低(因额外维护顺序) 更高
相关推荐
白狐_79810 小时前
考研408算法设计题保命策略:链表专题暴力解法精讲(2015 & 2019真题实战)
考研·算法·链表
ashiho12 小时前
【Redis】原理篇 3w字详解
数据库·redis·缓存·bootstrap
轻揉小乔 真新人1 天前
使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
运维·nginx·缓存
纵有疾風起1 天前
页面置换算法与实战机制:从 LRU 到内存映射文件
操作系统·408·lru·mmap·clock·页面置换·belady异常
小园子的小菜2 天前
Redis 核心原理深度解析:从数据结构、IO 模型到持久化机制
数据库·redis·缓存
BullSmall2 天前
Another Redis Desktop Manager(ARDM)下载指南
数据库·redis·缓存
nvd112 天前
ArgoCD 双层轮询深入拆解:从 redis-app.yaml 注册到缓存重建的完整链路
redis·缓存·argocd
xiaoxiangsiyan2 天前
LNMP + Redis Sentinel 高可用架构部署手册(续)
运维·网络·数据库·redis·缓存·架构·sentinel
難釋懷2 天前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard2 天前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机