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.
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
def __setitem__(self, key, value):
if key in self:
del self[key]
OrderedDict.__setitem__(self, key, value)
class LRUCache(object):
def __init__(self, capacity):
self.dict = LastUpdatedOrderedDict()
self.capacity = capacity
def get(self, key):
if key in self.dict:
r = self.dict[key]
self.dict[key] = r
return r
return -1
def set(self, key, value):
if key not in self.dict and self.capacity == len(self.dict):
item = self.dict.popitem(last=False)
self.dict[key] = value