146 LRU缓存

python 复制代码
class DLinkedList:

    def __init__(self, key = 0, val = 0):
        self.prev = None
        self.next = None
        self.val = val
        self.key = key

class LRUCache:

    def __init__(self, capacity: int):
        self.head = DLinkedList()
        self.tail = DLinkedList()
        self.head.next = self.tail
        self.tail.prev = self.head
        self.cache = {}
        self.capacity = capacity

    def get(self, key: int) -> int:
        if key in self.cache:
            node = self.cache[key]
            self.remove(node)
            self.movetoHead(node)
            return self.cache[key].val
        
        return -1


    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.val = value
            self.remove(node)
            self.movetoHead(node)
        else:

            if self.capacity == 0:
                del self.cache[self.tail.prev.key]
                self.remove(self.tail.prev)
                self.capacity += 1

            node = DLinkedList(key,value)
            self.cache[key] = node
            self.capacity -= 1
            self.movetoHead(node)

            
    
    def movetoHead(self, node):
        tmp = self.head.next
        self.head.next = node
        node.prev = self.head
        node.next = tmp
        tmp.prev = node

    def remove(self, node):
        prev = node.prev
        next = node.next
        prev.next = next
        next.prev = prev

重点:

操作模块化(remove, movetoHead);

双向链表,链表内保存key - value;

虚拟头尾节点。

相关推荐
江上鹤.14810 分钟前
Day36官方文档的阅读
python
嗝o゚11 分钟前
Flutter 无障碍功能开发最佳实践
python·flutter·华为
芝麻开门-新起点15 分钟前
第13-1章 Python地理空间开发
开发语言·python
秋刀鱼 ..1 小时前
2026年电力电子与电能变换国际学术会议 (ICPEPC 2026)
大数据·python·计算机网络·数学建模·制造
长安er1 小时前
LeetCode 83/237/82 链表删除问题-盒子模型
数据结构·算法·leetcode·链表·力扣
znhy_231 小时前
day35打卡
python
盼哥PyAI实验室1 小时前
12306反反爬虫策略:Python网络请求优化实战
网络·爬虫·python
重生之后端学习1 小时前
56. 合并区间
java·数据结构·后端·算法·leetcode·职场和发展
deephub1 小时前
DeepSeek-R1 与 OpenAI o3 的启示:Test-Time Compute 技术不再迷信参数堆叠
人工智能·python·深度学习·大语言模型
力江2 小时前
FastAPI 最佳架构实践,从混乱到优雅的进化之路
python·缓存·架构·单元测试·fastapi·分页·企业