
解题思路:
字典用来保存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)
本文详细介绍了一种基于字典和列表实现的LRU(最近最少使用)缓存机制。通过将最近使用的项放置在列表的最前面,以及利用字典来快速查找和更新缓存项,该机制有效地管理了缓存容量,确保了缓存的高效运行。
928

被折叠的 条评论
为什么被折叠?



