(力扣记录)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)
相关推荐
山峰哥16 小时前
Python爬虫实战:从零构建高效数据采集系统
开发语言·数据库·爬虫·python·性能优化·架构
历程里程碑16 小时前
LeetCode热题11:盛水容器双指针妙解
c语言·数据结构·c++·经验分享·算法·leetcode·职场和发展
Jay_Franklin1 天前
SRIM通过python计算dap
开发语言·python
是一个Bug1 天前
Java基础50道经典面试题(四)
java·windows·python
吴佳浩1 天前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
wadesir1 天前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878381 天前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill1 天前
哈希-02-最长连续序列
算法·leetcode·排序算法
liliangcsdn1 天前
python下载并转存http文件链接的示例
开发语言·python
Morwit1 天前
【力扣hot100】64. 最小路径和
c++·算法·leetcode