134. LRU缓存策略
为最近最少使用(LRU)缓存策略设计一个数据结构,它应该支持以下操作:获取数据(get)和写入数据(set)。
获取数据get(key):如果缓存中存在key,则获取其数据值(通常是正数),否则返回-1。
写入数据set(key, value):如果key还没有在缓存中,则写入其数据值。当缓存达到上限,它应该在写入新数据之前删除最近最少使用的数据用来腾出空闲位置。
解题思路:
利用一个排序字典OrderedDict,会根据放入元素的先后顺序进行排序。
当获取数据时,先将该元素弹出,然后在加入,这样就保证了排序字典的顺序,第一个永远是最近最少使用的。
在插入数据时,如果元素存在,同样先弹出再插入,如果cache已经满了,则删除第一个元素,然后再插入。
from collections import OrderedDict
class LRUCache:
"""
@param: capacity: An integer
"""
def __init__(self, capacity):
# do intialization if necessary
self.cache = OrderedDict()
self.capacity = capacity
"""
@param: key: An integer
@return: An integer
"""
def get(self, key):
# write your code here
if key not in self.cache:
return -1
value = self.cache.pop(key)
self.cache[key] = value
return value
"""
@param: key: An integer
@param: value: An integer
@return: nothing
"""
def set(self, key, value):
# write your code here
if key in self.cache:
self.cache.pop(key)
elif len(self.cache) == self.capacity:
#默认是last = True LIFO ,当last = False,FIFO
self.cache.popitem(last = False)
self.cache[key] = value