# LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制

实现 LRUCache 类:

 

进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

 

示例:

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4

 

提示:

## template ```python class LRUCache: def __init__(self, capacity): """ :type capacity: int """ self.maxlength = capacity self.array = {} self.array_list = [] def get(self, key): """ :type key: int :rtype: int """ value = self.array.get(key) if value is not None and self.array_list[0] is not key: index = self.array_list.index(key) self.array_list.pop(index) self.array_list.insert(0, key) value = value if value is not None else -1 return value def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if self.array.get(key) is not None: index = self.array_list.index(key) self.array.pop(key) self.array_list.pop(index) if len(self.array_list) >= self.maxlength: key_t = self.array_list.pop(self.maxlength - 1) self.array.pop(key_t) self.array[key] = value self.array_list.insert(0, key) ``` ## 答案 ```python ``` ## 选项 ### A ```python ``` ### B ```python ``` ### C ```python ```