LRU缓存机制-力扣146题
首先选择结构是哈希双链表,字典结构{key:node},双链表结构如图所示,(这里添加了伪头和伪尾节点,方便删除添加节点)
注:默认双链表头节点是最新使用,尾部是最久未使用
get方法:1、查询key是否在dict中,不在返回-1,在,返回node.val,同时将node移到头部
put方法:1、查询key是否在dict中,不在,创建node节点并加入dict,加入双链表头部,并且维护size是否超过规定容量,如果超过,则需要去除尾部节点,否则pass
在,则更改node.val,把该节点移入头部即可
节点移入头部操作:1、删除该节点, 2、将节点加入头部节点,(node.next = head.next node.prev = head head.next = node node.next.prev = node)
删除尾部节点:tail.prev = tail.prev.prev tail.prev.next = tail
1 class DlinkedNode: 2 def __init__(self,key = 0,value =0): 3 self.key = key 4 self.value =value 5 self.prev = None 6 self.next = None 7 8 class LRUCache: 9 10 def __init__(self, capacity: int):# 头尾节点方便简单 11 self.capacity = capacity 12 self.head = DlinkedNode() 13 self.tail = DlinkedNode() 14 self.head.next = self.tail 15 self.tail.prev = self.head 16 self.cache = dict() # 哈希 17 self.size = 0 18 19 def get(self, key: int) -> int: 20 if key not in self.cache.keys(): 21 return -1 22 node = self.cache[key] 23 self.movetoHead(node) 24 return node.value 25 26 def put(self, key: int, value: int) -> None: 27 if key not in self.cache.keys(): 28 node = DlinkedNode(key,value) 29 self.cache[key] = node 30 self.addtoHead(node) 31 self.size+=1 32 if self.size>self.capacity: 33 node = self.removeTail() 34 self.cache.pop(node.key) 35 self.size-=1 36 else: 37 node = self.cache[key] 38 node.value = value 39 self.movetoHead(node) 40 41 def movetoHead(self,node): 42 self.remove(node) 43 self.addtoHead(node) 44 45 def remove(self,node): 46 node.next.prev = node.prev 47 node.prev.next = node.next 48 49 def addtoHead(self,node): 50 node.next = self.head.next 51 node.prev = self.head 52 self.head.next = node 53 node.next.prev = node 54 55 def removeTail(self): 56 node = self.tail.prev 57 self.tail.prev = self.tail.prev.prev 58 self.tail.prev.next = self.tail 59 return node 60 61 # Your LRUCache object will be instantiated and called as such: 62 # obj = LRUCache(capacity) 63 # param_1 = obj.get(key) 64 # obj.put(key,value)