首页 技术 正文
技术 2022年11月14日
0 收藏 932 点赞 2,645 浏览 1745 个字

【题目】

运用你所掌握的数据结构,设计和实现一个  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(); }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,496
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,909
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,743
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,496
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,134
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298