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;

虚拟头尾节点。

相关推荐
闲人编程2 小时前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
Mr_Xuhhh5 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441335 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天5 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
Q_Q5110082855 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
SunnyDays10117 小时前
如何使用Python高效转换Excel到HTML
python·excel转html
Q_Q5110082857 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
Q_Q5110082858 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
汤姆yu8 小时前
2026版基于python大数据的旅游可视化及推荐系统
python·旅游·大数据旅游
angleoldhen8 小时前
简单的智能数据分析程序
python·信息可视化·数据分析