(力扣记录)146. LRU 缓存

发布时间:2024年01月18日

数据类型:链表

时间复杂度:O(1)

空间复杂度:O(N)

代码实现:

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)

文章来源:https://blog.csdn.net/Wilson_Lin_01/article/details/135578698
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。