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;

虚拟头尾节点。

相关推荐
吴佳浩6 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
superman超哥7 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q7 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A7 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
阿昭L8 小时前
leetcode链表相交
算法·leetcode·链表
徐先生 @_@|||8 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
Mqh1807628 小时前
day45 简单CNN
python
学习者0079 小时前
python 下载离线库方法
python
声声codeGrandMaster9 小时前
AI之模型提升
人工智能·pytorch·python·算法·ai
魔镜前的帅比9 小时前
多 Agent 架构:Coordinator + Worker 模式
python·ai