这道题不会,一开始题目都看不懂,直接学习代码吧
class LRUCache:
def __init__(self, capacity: int):
# list 有序记录最近访问的key di记录key value 值
self.li = []
self.di = dict()
self.capacity = capacity
def get(self, key: int) -> int:
#get一次算一次缓存
if key in self.li:
# 重新更新最近访问的key
self.li.remove(key)
self.li.append(key)
return self.di[key]
return -1
def put(self, key: int, value: int) -> None:
if key in self.li:
self.li.remove(key)
elif len(self.li) == self.capacity:
self.di.pop(self.li[0])
self.li.remove(self.li[0])
self.li.append(key)
self.di[key]=value