+ Hash-based list of LRU algorithm.
-
When access to a hot, remove it from its original location, plug it into the header of the list
-
In order to read and delete the time complexity is O (1), using the information stored hash keys hotspot
class LRUCaceh(): def __init__(self, size=5): ''' Default queue length is 5 Use the list to maintain, use a dictionary to look up ''' self.size = size self.cache = dict() self.key = [] def get(self, key): ''' Gets the value of the cache key ''' if self.cache.get(key): self.key.remove(key) self.key.insert(0, key) return self.cache[key] return None def set(self, key, value): ''' Setting the cache, the cache to achieve elimination ''' if self.cache.get(key): self.cache.pop(key) self.cache[key] = value self.key.remove(key) self.key.insert(0, key) elif len(self.key) == self.size: old_key = self.key.pop() self.key.insert(0, key) self.cache.pop(old_key) self.cache[key] = value else: self.key.insert(0, key) self.cache[key] = value