LeetCode 146. LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
class LRUCache:
def __init__(self, capacity: int):
self.maxsize = capacity
self.lrucache = OrderedDict()
def get(self, key: int) -> int:
if key in self.lrucache:
# 如果存在,将其移动到字典的最后面,表示最新访问过
self.lrucache.move_to_end(key)
# 如果存在,返回key对应的value,否则返回-1
return self.lrucache.get(key, -1)
def put(self, key: int, value: int) -> None:
if key in self.lrucache:
# 如果之前存在,先删除
del self.lrucache[key]
# 放入dict里面
self.lrucache[key] = value
# 如果超出缓存, 删除最早进去的那一个
if len(self.lrucache) > self.maxsize:
self.lrucache.popitem(last = False)
补充:OrderedDict
Python中的字典对象可以以“键:值”的方式存取数据。OrderedDict是它的一个子类,实现了对字典对象中元素的排序。
popitem(last=True)
:
该方法返回并删除一对键值.如果last为True(默认值),则为LIFO(后进先出);否则为FIFO(先进先出).
move_to_end(key, last=True)
:
将现有的key移到字典的一端.如果last为True(默认值),移动到末尾(最新加入的元素);否则,移动到开头(最早加入的元素).