这道题实在是没看懂参考了B站这个大神,大概看懂了
https://www.bilibili.com/video/av49870345?from=search&seid=13851888023627148872
主要是要定义一个双向的链表和一个字典来处理。
双向链表可以可访问它的上一个元素和下一个元素。
字典可以储存(每个双向链表的key,和它们对应的双向链表)
同时还需要两个额外的函数
一个是_remove(),用于移除对应的双向链表节点
一个是_add(),用于在双向链表最后加上对应的节点
class Node(object):
def __init__(self,key,value):
self.key = key
self.value = value
self.next = None
self.prev = None
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.dic = dict()
self.head = Node(0,0)
self.tail = Node(0,0)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.dic:
node = self.dic[key]
self._remove(node)
self._add(node)
return node.value
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.dic:
self._remove(self.dic[key])
node = Node(key,value)
self.dic[key] = node
self._add(node)
if len(self.dic) > self.capacity:
node_del = self.head.next
del self.dic[node_del.key]
self._remove(node_del)
def _remove(self,node):
p = node.prev
n = node.next
p.next = n
n.prev = p
def _add(self,node):
p = self.tail.prev
p.next = node
node.next = self.tail
node.prev = p
self.tail.prev = node
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)