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 deque
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.map = {}
self.queue = deque(maxlen=capacity)
# @return an integer
def get(self, key):
if self.map.has_key(key):
return self.map[key]
else:
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if self.get(key) != -1:
self.map[key] = value
else:
if len(self.queue) == self.queue.maxlen:
deletedKey = self.queue.popleft()
del self.map[deletedKey]
self.queue.append(key)
self.map[key] = value