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;

虚拟头尾节点。

相关推荐
xcbrand15 小时前
文旅行业品牌策划公司找哪家
大数据·运维·人工智能·python
好家伙VCC15 小时前
**发散创新:基于Rust的轻量级权限管理库设计与开源许可证实践**在现代分布式系统中,**权限控制(RBAC
java·开发语言·python·rust·开源
Dxy123931021616 小时前
Python序列标注模型上下文纠错详解
开发语言·python
ZhengEnCi16 小时前
P2H-Python字符串格式化完全指南-format和f-string的Python编程利器
python
HaiXCoder16 小时前
python从入门到精通-第5章: 函数式编程 — Python的函数式风格
python
HaiXCoder16 小时前
python从入门到精通-第0章: 思维模式碰撞
python
HaiXCoder16 小时前
python从入门到精通-第3章: 数据结构 — Python的"瑞士军刀
python
Orange_sparkle16 小时前
learn claude code学习记录-S02
java·python·学习
小郑加油16 小时前
python学习Day1:python的安装与环境搭载
python·学习·小白记录,保姆式教程
Zewen PAN16 小时前
wsl安装pytorch
人工智能·pytorch·python