LRU Cache
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.
My first thought is to use min heap to track the usage; and use another hashmap to guarantee constant complexity for get method. However, heap structure is not helpful for "recently used". Instead, we can use doubly linked list to store the <key, value> pair. Hashmap is still required for get method.
The logic is:
get(key): use hashmap to find the corresponding node in the linked list. Remove the node, and then add it to the tail, i.e., this node has been used recently.
set(key, value): search the hashmap, if the node already exists, change its value; otherwise, create a new node, add it to the tail. If the size exceeds the capacity, remove the head (least recently used cache).
Comments
Post a Comment