题目:
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.
Follow up:
Could you do both operations in O(1) time complexity?
思路:
这是我个人非常喜欢的一道设计题。由于要求必须在O(1)的时间内get到一个key的value,所以可以很自然地想到采用哈希表。然而这道题目的难度在于我们需要维护一个访问列表,也就是最近访问的节点要位于列表前端,每次访问完一个节点之后,这个访问列表都需要做适当更新。那么自然而然地可以想到list这种数据结构,因为只要我们有需要访问的节点的迭代器,那么在list中对它进行插入、删除或者修改的时间复杂度都是O(1)。所以我们的数据结构也就出来了:采用list来维护一个访问队列;采用哈希表实现快速访问。哈希表的键是我们题目中的key,值可以设置为访问队列中的对应元素的迭代器。由于当访问节点超过容量的时候,需要删除最久没有被访问的节点,所以我们在访问队列的元素中同时存储key值,这样在删除的时候,就可以通过访问队列中的最后一个元素,来获得在哈希表中需要删除的元素的key值,从而实现快速删除。
代码:
class LRUCache{
public:
LRUCache(int capacity) {
n = capacity;
}
int get(int key) {
auto it = hash_map.find(key);
if(it == hash_map.end()) {
return -1;
}
else {
element_list.splice(element_list.begin(), element_list, it->second); // move the iterator to the first
return it->second->second;
}
}
void put(int key, int value) {
auto it = hash_map.find(key);
if(it != hash_map.end()) {
it->second->second = value;
element_list.splice(element_list.begin(), element_list, it->second); // move the iterator to the first
}
else {
element_list.push_front(std::pair<int, int>(key, value));
hash_map[key] = element_list.begin();
if(element_list.size() > n) {
hash_map.erase(element_list.back().first); // delete this key from hash_map
element_list.pop_back();
}
}
}
private:
unordered_map<int, list<pair<int, int>>::iterator> hash_map;
list<pair<int, int>> element_list;
int n;
};