在LeetCode上看到这么一道题:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
get(key):获取key对应的value,如果key不在cache中那么返回-1(value 总是为正数);
set(key, value):如果key在cache中则更新它的value;如果不在则插入,如果cache已满则先删除最近最少使用的一项后在插入。
对于get,如果key在cache中,那个get(key)表示了对key的一次访问;而set(key,value)则总是表示对key的一次访问。
使用一个list来记录访问的顺序,最先访问的放在list的前面,最后访问的放在list的后面,故cache已满时,则删除list[0],然后插入新项;
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.cache = {}
self.used_list = []
self.capacity = capacity
# @return an integer
def get(self, key):
if key in self.cache:
if key != self.used_list[-1]:
self.used_list.remove(key)
self.used_list.append(key)
return self.cache[key]
else:
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if key in self.cache:
self.used_list.remove(key)
elif len(self.cache) == self.capacity:
self.cache.pop(self.used_list.pop(0))
self.used_list.append(key)
self.cache[key] = value