代码思路:
Python 默认是用 dict 存储属性的,每次用 . 访问属性都需要查字典。如果声明 slots 就不会创建字典,而是改用指针偏移量直接拿到属性对象。所以即节省了内存(没有字典)又节省了时间(省去查字典的过程)。
class Node:
__slots__ = 'prev','next','key','value'
def __init__(self,key=0,value=0):
self.key = key
self.value = value
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dummy = Node()
self.dummy.prev = self.dummy
self.dummy.next = self.dummy
self.key_to_node = dict()
def get_node(self,key:int) -> Optional[Node]:
if key not in self.key_to_node: #没有的话
return None
node = self.key_to_node[key] #有
self.remove(node)
self.push_front(node) #放到最前面
return node
def get(self, key: int) -> int:
node = self.get_node(key)
return node.value if node else -1
def put(self, key: int, value: int) -> None:
node = self.get_node(key)
if node:
node.value = value #更新value
return
self.key_to_node[key] = node = Node(key,value)
self.push_front(node)
if len(self.key_to_node) > self.capacity:
back_node = self.dummy.prev
del self.key_to_node[back_node.key]
self.remove(back_node)
def remove(self, x:Node) -> None:
x.prev.next = x.next
x.next.prev = x.prev
def push_front(self, x:Node) -> None:
x.prev = self.dummy
x.next = self.dummy.next
x.prev.next = x
x.next.prev = x