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)
相关推荐
IT·小灰灰1 天前
告别“翻墙“烦恼:DMXAPI让Gemini-3-pro-thinking调用快如闪电
网络·人工智能·python·深度学习·云计算
山海青风1 天前
语音合成 - 用 Python 合成藏语三大方言语音
开发语言·python·音视频
mikejahn1 天前
爬取CECS网站征求意见栏目的最新信息
python
占疏1 天前
dify API访问工作流/聊天
开发语言·数据库·python
aningxiaoxixi1 天前
TTS 之 PYTHON库 pyttsx3
开发语言·python·语音识别
深蓝海拓1 天前
PySide6从0开始学习的笔记(三) 布局管理器与尺寸策略
笔记·python·qt·学习·pyqt
数据科学项目实践1 天前
建模步骤 3 :数据探索(EDA) — 1、初步了解数据:常用函数
人工智能·python·机器学习·数据挖掘·数据分析·pandas·数据可视化
Chen--Xing1 天前
2025鹏城杯 -- Crypto -- RandomAudit详解
python·密码学·ctf·鹏城杯
一瞬祈望1 天前
PyTorch 图像分类完整项目模板实战
人工智能·pytorch·python·深度学习·分类
坐吃山猪1 天前
BrowserUse12-源码-MCP模块
python·llm·playwright·browser-use