Problem
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
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.
The cache is initialized with a positive capacity.
Follow up: Could you do both operations in O(1) time complexity?
Example:
1 | |
Explanation
-
We can use doubly linked list storing class node to achieve adding and removing in $O(1)$ time by using
prevandnextpointer. When we do get, we can use hashmap to achieve getting the value by key in $O(1)$ time. -
Besides
putandgetfunction, we also need to haveremoveandsetHeadfunction. If we run get on a node, then that node need to set it as head. If we have number ofcapacitynode in our linked list, then if we put one more node, we need toremovethe tail node.
Solution
1 | |