【题目】
运用你所掌握的数据结构,设计和实现一个 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
【解题思路】
见博客:左神算法进阶班5_4设计可以变更的缓存结构(LRU)
【代码】
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
} int get(int key) {
if (map.find(key) == map.end())
return -;
Node* p = map[key];
update(p);//更新使用频率
return p->val;
} void put(int key, int value) {
if (map.find(key) == map.end())//不存在就存入
{
if (this->map.size() == this->capacity)//缓存空间已满
{
Node* p = this->head->next;
this->head->next = p->next;//删除位于链表头部的最不常用的节点
if (p->next == nullptr)//只有一个数据
end = head;
else
p->next->pre = head;
map.erase(p->key);//从表中删除,以留出空间
delete p;
}
Node* p = new Node(key, value);//新插入的数据在链表尾
this->end->next = p;
p->pre = end;
end = p;
map[key] = p;//存入数据
}
else//存在,但要更新数的使用频率
{
Node* p = map[key];//得到在链表中的位置
p->val = value;//更新数据值
update(p);//更新使用频率
}
} private:
struct Node
{
int key;
int val;
Node* pre;
Node* next;
Node(int k, int v) :key(k), val(v), pre(nullptr), next(nullptr) {}
}; int capacity = ;
hash_map<int, Node*>map;
Node* head = new Node(' ', -);//指向链表的头
Node* end = head;//指向链表的尾
void update(Node* p)
{
if (p == end)
return;//p在链表尾部就不用移动了
Node* q = p->pre;
q->next = p->next;
p->next->pre = q;
end->next = p;
p->pre = end;//更新p的使用率,并挪至链表尾部
end = p;
}
}; /**
* 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);
*/ void Test()
{
LRUCache* rr = new LRUCache();
rr->put(, );
cout << rr->get() << endl;
rr->put(, );
cout << rr->get() << endl;
rr->get();
rr->put(, );
rr->get();
rr->get(); }