Design and implement a data structure forLeast Recently Used (LRU) cache. It should support the following operations:getandput.
get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.
Follow up:
Could you do both operations inO(1)time complexity?
```python
from collections import OrderedDict
class LRUCache:
"""
@param: capacity: An integer
"""
def __init__(self, capacity):
# do intialization if necessary
self.capacity = capacity
self.cache = OrderedDict()
"""
@param: key: An integer
@return: An integer
"""
def get(self, key):
# write your code here
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache.get(key)
"""
@param: key: An integer
@param: value: An integer
@return: nothing
"""
def set(self, key, value):
# write your code here
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
self.cache.move_to_end(key)
```