[Python手撕]LRU

Duancf發表於2024-09-01
class Node:
    def __init__(self, key=0, value=0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.length = 0
        self.map = {}
        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key: int) -> int:
        if key in self.map:
            self.remove(self.map[key])
            self.refresh(self.map[key])
            return self.map[key].value
        else:
            return -1
        

    def put(self, key: int, value: int) -> None:
        if key in self.map:
            self.map[key].value = value
            self.remove(self.map[key])
            self.refresh(self.map[key])
        else:
            if self.length == self.capacity:
                t = self.head.next.key
                self.remove(self.head.next)
                del self.map[t]
                node = Node(key, value)
                self.refresh(node)
                self.map[key] = node
            else:
                node = Node(key, value)
                self.refresh(node)
                self.map[key] = node
                self.length += 1

    def remove(self, node):
        node.next.prev = node.prev
        node.prev.next = node.next

    def refresh(self, node):
        node.prev = self.tail.prev
        self.tail.prev.next = node
        node.next = self.tail
        self.tail.prev = node

    def show(self):
        cur = self.head.next
        while cur.next:
            print(cur.key,cur.value, end="|")
            cur = cur.next
        print()


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

相關文章