Problem Summary
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.
Solution
We can use linked list together with unordered map to solve this problem.
First, we use a linked list L to record pairs of keys and values. Each time we insert a new pair (key,value), we use the map to mark the position of it.
Then, for each get(key) operation, we can locate the pair (key,value) using the map in O(1) time. We also need to move the pair to the beginning of the linked list, since it is just used. Don’t forget to modify map[key] as the position of pair (key,value) changed.
As for the set(key,value) operation,
- If (key,previous_value) already exits in the list, we erase it and insert the new pair.
- If key is not already present, we need to check the capacity first. If the cache has reached its capacity, we erase the least recently used item, i.e. the pair at the end of the linked list. Then we insert the new pair to the beginning.
And of course, we need to maintain the map in the above process.
The time complexities of get and set operations are both O(1), since the map is unordered.
Code
|
|