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;

虚拟头尾节点。

相关推荐
huanxiangcoco2 分钟前
73. 矩阵置零
python·leetcode·矩阵
源代码:趴菜20 分钟前
LeetCode118:杨辉三角
算法·leetcode·动态规划
luluvx20 分钟前
LeetCode[中等] 74.搜索二维矩阵
算法·leetcode·矩阵
一晌小贪欢21 分钟前
Python基础知识——字典排序(不断补充)
python·json·python基础·字典·字典排序·python学习
YOLO数据集工作室31 分钟前
Python介绍
开发语言·python
Hiweir ·1 小时前
机器翻译之创建Seq2Seq的编码器、解码器
人工智能·pytorch·python·rnn·深度学习·算法·lstm
不染_是非2 小时前
Django学习实战篇六(适合略有基础的新手小白学习)(从0开发项目)
后端·python·学习·django
star数模2 小时前
2024“华为杯”中国研究生数学建模竞赛(E题)深度剖析_数学建模完整过程+详细思路+代码全解析
python·算法·数学建模
Mero技术博客2 小时前
第二十节:学习Redis缓存数据库实现增删改查(自学Spring boot 3.x的第五天)
数据库·学习·缓存
sjsjs112 小时前
【数据结构-扫描线】力扣57. 插入区间
数据结构·算法·leetcode