解题思路:
字典用来保存key与value之间的关系,list用来保存最近最少使用机制,最近使用的放在最前面
class LRUCache:
def __init__(self, capacity: int):
self.maxlength = capacity
self.array = {}
self.array_list = []
def get(self, key: int) -> int:
value = self.array.get(key)
if value:
index = self.array_list.index(key)
self.array_list.pop(index)
self.array_list.insert(0, key)
return value
else:
return -1
def put(self, key: int, value: int) -> None:
new_value = self.array.get(key)
if new_value:
index = self.array_list.index(key)
self.array_list.pop(index)
if len(self.array_list) >= self.maxlength:
del_key = self.array_list[-1]
self.array_list.pop(-1)
self.array.pop(del_key)
self.array_list.insert(0, key)
self.array[key] = value
#print(self.array_list)
#print(self.array)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)