1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class ListNode: def __init__(self, key=0, val=0, prev=None, next=None): self.key = key self.val = val self.prev = prev self.next = next
class LRUCache:
def __init__(self, capacity: int): self.capacity = capacity self.currentSize = 0 self.dic = {} self.head = ListNode() self.tail = ListNode() self.head.next = self.tail self.tail.prev = self.head
def get(self, key) -> int: if key in self.dic: self.move_to_end(key) return self.dic[key].val else: return -1
def put(self, key, value: int) -> None:
if self.capacity == 0: return
if key in self.dic: self.dic[key].val = value self.move_to_end(key) else: if self.currentSize == self.capacity: self.delete(self.head.next.key) self.currentSize -= 1 self.append(key, value) self.currentSize += 1
def append(self, key, value: int) -> None: nodePrev = self.tail.prev nodeNext = self.tail
node = ListNode(key, value, nodePrev, nodeNext) self.dic[key] = node
nodePrev.next = node nodeNext.prev = node
def delete(self, key) -> ListNode: node = self.dic.pop(key)
nodePrev = node.prev nodeNext = node.next
nodePrev.next = nodeNext nodeNext.prev = nodePrev
return node
def move_to_end(self, key) -> None: popped = self.delete(key) self.append(popped.key, popped.val)
|