(力扣记录)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)
相关推荐
yanghuashuiyue15 分钟前
LangGraph框架研究-开发测试
python·langgraph
禹凕17 分钟前
PyTorch——安装(有无 NVIDIA 显卡的完整配置方案)
人工智能·pytorch·python
卷心菜狗21 分钟前
Python进阶--迭代器
开发语言·python
dragen_light21 分钟前
5.ROS2-Topics-Publisher-Subscriber
python
jr-create(•̀⌄•́)24 分钟前
LeakyRelu链式法则
开发语言·python·深度学习
vx_biyesheji00011 小时前
计算机毕业设计:Python股价预测与可视化系统 Flask框架 数据分析 可视化 机器学习 随机森林 大数据(建议收藏)✅
python·机器学习·信息可视化·数据分析·flask·课程设计
FakeOccupational4 小时前
【数学 密码学】量子通信:光的偏振&极化的量子不确定性特性 + 量子密钥分发 BB84算法步骤
算法·密码学
ZhengEnCi6 小时前
S10-蓝桥杯 17822 乐乐的积木塔
算法
贾斯汀玛尔斯6 小时前
每天学一个算法--拓扑排序(Topological Sort)
算法·深度优先
大龄程序员狗哥6 小时前
第25篇:Q-Learning算法解析——强化学习中的经典“价值”学习(原理解析)
人工智能·学习·算法