LeetCode-146.LRU缓存(Python)

此题看题解

题目链接

python 复制代码
class ListNode:
    def __init__(self, key=None, value=None):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

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

    def get(self, key: int) -> int:
        if key in self.cache:
            node = self.cache[key]
            self._move_to_head(node)
            return node.value
        else:
            return -1

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.value = value
            self._move_to_head(node)
        else:
            if len(self.cache) == self.capacity:
                self._remove_tail()
            node = ListNode(key, value)
            self.cache[key] = node
            self._add_to_head(node)

    def _move_to_head(self, node: ListNode) -> None:
        self._remove_node(node)
        self._add_to_head(node)

    def _remove_node(self, node: ListNode) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_to_head(self, node: ListNode) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _remove_tail(self) -> None:
        node = self.tail.prev
        self._remove_node(node)
        del self.cache[node.key]
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
相关推荐
小小测试开发3 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想4 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波4 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
8Qi85 小时前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
copyer_xyf5 小时前
Python 异常处理
前端·后端·python
麻雀飞吧6 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy6 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.6 小时前
【01】Python 机器学习
开发语言·python
为爱停留6 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t6 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python