146. LRU Cache
https://leetcode.com/problems/lru-cache/
solution
复合数据结构通常采用 unordered_map 或 map 辅助记录,加速寻址;配上 vector 或 list数据储存,加速连续选址或删除值
1.新数据放到链表的开头
2.数据被访问后,也需要放到链表开头
3.当超过LRU的容量之后,将链表尾部的数据删除
双向链表+哈希
# 一个类似字典item的node, 同时记录其前后的位置
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.cache = {} # key到Node的索引, 对于linked list, tree, graph等通过局部逐渐访问, 建立一个全局的快速访问
self.head = Node() # dummy head and tail
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if key not in self.cache:
return -1
node = self.cache[key]
self.remove_node(node)
self.add_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
if key in self.cache:
node = self.cache[key]
node.value = value # 记得更新value
self.remove_node(node)
self.add_to_head(node)
else:
node = Node(key, value)
self.cache[key] = node
self.add_to_head(node)
if len(self.cache) > self.capacity:
self.remove_tail()
def remove_node(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def add_to_head(self, node):
self.head.next.prev = node
node.next = self.head.next
self.head.next = node
node.prev = self.head
def remove_tail(self):
del self.cache[self.tail.prev.key]
node = self.tail.prev
self.remove_node(node)时间复杂度:O(1) 空间复杂度:O(1)
时间复杂度:O() 空间复杂度:O()
follow up
多线程版本LRU
multiprocessing库: cpu-intensive 任务用 processPool, 如果是 io-intensive 任务用 threadPool
多进程: 多核CPU上并行执行,资源和变量不共享,需要通过管道队列通信,更适合计算密集型
多线程: CPU单核上互斥锁串行执行,资源共享。由于python GIL,一个进程当中如果存在多个线程,也只能在单核CPU上顺序执行,不能利用多个CPU,更适合IO密集型
MultiCache调用
https://www.1point3acres.com/bbs/thread-1104232-1-1.html
ordered_dict
时间复杂度:O() 空间复杂度:O()
Last updated