Your task is to design and implement a data structure for a Least Recently Used (LRU) cache. The cache should support the following operations:
get(key): Retrieve the value of the key if it exists in the cache, otherwise return -1.put(key, value): Insert or update the value of the key. If the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item.In this context, used means any access or modification of a key. The least recently used (LRU) item is the key that has not been accessed or updated for the longest time. When the cache is full, this item is removed to make space for new entries.
l = LRUCache(1) l.put(1, 1) l.put(1, 2) l.get(1)
[2]
l = LRUCache(2) l.put(1, 1) l.put(2, 2) l.get(2) l.get(1) l.put(3, 3) l.get(2)
[2, 1, -1]
l = LRUCache(1) l.put(1, 1) l.put(1, 2) l.get(1)
[2]