146. LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get
和 写入数据 put
。
获取数据get(key)
- 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value)
- 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
解题思路: LRU一般是用链表来模拟,解单纯的LRU题应该不难,但是解的优雅还是需要训练的,然后此题提出要求,put/get操作需要在时间复杂度为O(1)下完成,那么意味着,只用链表解题肯定不行,因为我们在移动节点之前需要通过key找到这个节点,只能线性查找,若想加速查找并且以时间复杂度为O(1)查找,则需要用到hashmap,这里我们用hashmap存放key到节点迭代器的映射,至此即可解题。另外对于STL中list操作常用的是push_front/back,pop_front/back,insert,通过这三个虽然能实现链表节点的移动,但是不够优雅,这里介绍list的另一个API,splice.
————————
std::list::splice,将一个链表某个位置的节点移动到另一个链表某个位置,若这两个链表相同,则实现的是链表内节点的移动
void splice (iterator position, list& x, iterator i); // position in List A, list& x is List B, i in List B
splice的作用是将链表B上迭代器i所指的节点移动到链表A上迭代器position所指的位置。
// LRU
// Time complexity of all operation: O(1), space: O(1)
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
auto it = mp.find(key);
if (it != mp.end()) {
lru.splice(lru.begin(), lru, it->second.first);
return it->second.second;
} else {
return -1;
}
}
void put(int key, int value) {
auto it = mp.find(key);
if (it != mp.end()) {
lru.splice(lru.begin(), lru, it->second.first);
it->second.second = value;
} else {
lru.push_front(key);
mp[key] = make_pair(lru.begin(), value);
if (lru.size() > capacity) {
int k = *(lru.rbegin());
auto it = mp.find(k);
mp.erase(it);
lru.pop_back();
}
}
}
private:
list<int> lru;
unordered_map<int, pair<list<int>::iterator, int>> mp;
int capacity;
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
————————————
对一些经典算法,最好能记住最优(优雅)的解法,比如这里的LRU cache,可以阅读参考资料中的博客,记住标答。
————————————
参考资料:
http://www.cplusplus.com/reference/list/list/
http://www.cplusplus.com/reference/list/list/splice/
https://www.cnblogs.com/grandyang/p/4587511.html