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)
相关推荐
zzc9216 分钟前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
编程有点难21 分钟前
Python训练打卡Day43
开发语言·python·深度学习
GalaxyPokemon28 分钟前
LeetCode - 148. 排序链表
linux·算法·leetcode
2301_8050545628 分钟前
Python训练营打卡Day48(2025.6.8)
pytorch·python·深度学习
LjQ204035 分钟前
网络爬虫一课一得
开发语言·数据库·python·网络爬虫
哆啦A梦的口袋呀1 小时前
基于Python学习《Head First设计模式》第九章 迭代器和组合模式
python·学习·设计模式
sponge'1 小时前
opencv学习笔记2:卷积、均值滤波、中值滤波
笔记·python·opencv·学习
databook2 小时前
概率图模型:机器学习的结构化概率之道
python·机器学习·scikit-learn
拾回程序猿的圈圈∞2 小时前
实战二:开发网页端界面完成黑白视频转为彩色视频
python·ai编程
亚林瓜子2 小时前
AWS Elastic Beanstalk + CodePipeline(Python Flask Web的国区CI/CD)
python·ci/cd·flask·web·aws·beanstalk·codepipeline