面试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() 支持 不支持
内存占用 更高(维护双向链表) 更低
性能 略低(因额外维护顺序) 更高
相关推荐
萌>__<新1 天前
力扣打卡每日一题————最小覆盖子串
数据结构·算法·leetcode·滑动窗口·哈希表
ada7_1 天前
LeetCode(python)230.二叉搜索树中第k小的元素
python·算法·leetcode·链表
长安er1 天前
LeetCode 83/237/82 链表删除问题-盒子模型
数据结构·算法·leetcode·链表·力扣
力江1 天前
FastAPI 最佳架构实践,从混乱到优雅的进化之路
python·缓存·架构·单元测试·fastapi·分页·企业
屋外雨大,惊蛰出没1 天前
小白安装Redis
数据库·redis·缓存
R-G-B1 天前
哈希表(hashtable),哈希理论,数组实现哈希结构 (C语言),散列理论 (拉链发、链接发),散列实现哈希结构,c++ 实现哈希
c语言·哈希算法·散列表·哈希表·数组实现哈希结构·散列实现哈希结构·c++ 实现哈希
六毛的毛1 天前
重排链表问题
数据结构·链表
Maiko Star1 天前
基于Redis ZSet实现多维度题目贡献度排行榜
数据库·redis·缓存
linsa_pursuer2 天前
回文链表算法
java·算法·链表
pingcode2 天前
IDEA清除缓存
缓存·intellij-idea