Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
Example 1:
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Constraints:
class ListNode:
def __init__ (self, key, val):
self.key = key
self.val = val
self.pre = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dict = {}
self.head = ListNode(-1, -1)
self.tail = ListNode(-1, -1)
self.head.next = self.tail
self.tail.pre = self.head
def get(self, key: int) -> int:
if key not in self.dict:
return -1
node = self.dict[key]
self.remove(node)
self.add(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.dict:
old_node = self.dict[key]
self.remove(old_node)
node = ListNode(key, value)
self.dict[key] = node
self.add(node)
if len(self.dict) > self.capacity:
node_to_delete = self.head.next
self.remove(node_to_delete)
del self.dict[node_to_delete.key]
def add(self, node: ListNode):
previous_end = self.tail.pre
previous_end.next = node
node.pre = previous_end
node.next = self.tail
self.tail.pre = node
def remove(self, node: ListNode):
node.pre.next = node.next
node.next.pre = node.pre
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
Complexity Analysis
import collections
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dict = collections.OrderedDict()
def get(self, key: int) -> int:
if key not in self.dict:
return -1
self.dict.move_to_end(key)
return self.dict[key]
def put(self, key: int, value: int) -> None:
if key in self.dict:
self.dict.move_to_end(key)
self.dict[key] = value
if len(self.dict) > self.capacity:
self.dict.popitem(False)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)