See this problem on the 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 (would 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 item used before a new item. Design a LRU cache, realize two functions: (Cache in the store (key,value) key value pairs)
Get (Key): Gets the value of the key and returns 1 if the key is not in the cache (value is always positive);
Set (key, value): If the key in the cache update its value, if it is not inserted, if the cache is full, first delete the least recently used after the insertion.
For GET, if key is in cache, that get (key) represents an access to key, and set (Key,value) always represents an access to key.
Use a list to record the order of access, the first access is placed in front of the list, the last access is placed behind the list, so the cache is full, then delete list[0], and then insert the new item;
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 K EY!= 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, a 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