(力扣记录)146. LRU 缓存

数据类型:链表

**时间复杂度:**O(1)

**空间复杂度:**O(N)

代码实现:

python 复制代码
class Node:

    def __init__(self, key=-1, value=-1):
        self.key = key
        self.val = value
        self.next = None
        self.prev = None

class LRUCache:

    def __init__(self, capacity: int):
        self.map = dict()
        self.cap = capacity
        self.left = Node()
        self.right = Node()
        self.right.prev = self.left
        self.left.next = self.right

    def pop(self, node: Node):
        node.prev.next, node.next.prev = node.next, node.prev

    def push(self, node: Node):
        last = self.right.prev
        last.next = node
        node.prev, node.next = last, self.right
        self.right.prev = node

    def get(self, key: int) -> int:
        if key not in self.map: return -1
        self.pop(self.map[key])
        self.push(self.map[key])
        return self.map[key].val

    def put(self, key: int, value: int) -> None:
        if key in self.map:
            self.pop(self.map[key])
        elif self.cap == len(self.map):
            self.map.pop(self.left.next.key)
            self.pop(self.left.next)
        self.push(Node(key, value))
        self.map[key] = self.right.prev
        


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
相关推荐
吴佳浩1 天前
大模型量化部署终极指南:让700亿参数的AI跑进你的显卡
人工智能·python·gpu
Hcoco_me1 天前
大模型面试题17:PCA算法详解及入门实操
算法
跨境卫士苏苏1 天前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代
大数据·人工智能·算法·亚马逊·防关联
diegoXie1 天前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
七牛云行业应用1 天前
解决OSError: No space left... 给DeepSeek Agent装上无限云硬盘
python·架构设计·七牛云·deepseek·agent开发
云雾J视界1 天前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
Xの哲學1 天前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算
BoBoZz191 天前
CutWithScalars根据标量利用vtkContourFilter得到等值线
python·vtk·图形渲染·图形处理
失散131 天前
Python——1 概述
开发语言·python
夏乌_Wx1 天前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode