题目描述(Hard)
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?
题目链接
https://leetcode.com/problems/lru-cache/description/
Example 1:
LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4
算法分析
使用双向链表及哈希表保证查找、插入及删除都有较高的性能:
- 哈希表保存每个节点地址,可以基本保证在O(1)时间内查找节点;
- 双向链表插入和删除的效率高,单向链表插入和删除时,还要查找节点的前驱节点;
具体实现方法:
- 越靠近链表的头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近访问最少;
- 访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中的该节点的地址;
- 插入节点时,如果cache的size达到了上限capacity,则删除尾部节点,同时要在hash表中删除对应的项,新节点插入链表头部。
提交代码:
扫描二维码关注公众号,回复:
3123367 查看本文章
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (cacheMap.find(key) == cacheMap.end()) return -1;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->value;
}
void put(int key, int value) {
if (cacheMap.find(key) == cacheMap.end())
{
// 满容量则删除尾部元素
if (cacheMap.size() == capacity)
{
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
// 在头部插入元素
cacheList.push_front(CacheNode(key, value));
cacheMap[key] = cacheList.begin();
}
else
{
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}
private:
struct CacheNode {
int key;
int value;
CacheNode(int k, int v) : key(k), value(v) {}
};
list<CacheNode> cacheList;
unordered_map<int, list<CacheNode>::iterator> cacheMap;
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);
*/