usedlist保存访问的顺序, capacity保存lru的容量,mapping保存映射的数组
class LRUCache:
def __init__(self, capacity: int):
self.usedlist = []
self.capacity = capacity
self.mapping = {}
def get(self, key: int) -> int:
if not self.mapping or key not in self.mapping:
return -1
else:
value = self.mapping[key]
newlist = [key]
for num in self.usedlist:
if num != key:
newlist.append(num)
self.usedlist = newlist[:]
return value
def put(self, key: int, value: int) -> None:
if key in self.mapping:
self.mapping[key] = value
newlist = [key]
for num in self.usedlist:
if num != key:
newlist.append(num)
self.usedlist = newlist[:]
return
if len(self.usedlist) < self.capacity:
self.usedlist.insert(0,key)
else:
popv = self.usedlist[-1]
self.usedlist.pop()
del self.mapping[popv]
self.usedlist.insert(0,key)
self.mapping[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)