LRU缓存策略
来源:互联网 发布:ubuntu ssh安装包下载 编辑:程序博客网 时间:2024/04/30 08:38
题目:为最近最少使用(LRU)缓存策略设计一个数据结构,它应该支持以下操作:获取数据(get)和写入数据(set)。获取数据get(key):如果缓存中存在key,则获取其数据值(通常是正数),否则返回-1。写入数据set(key, value):如果key还没有在缓存中,则写入其数据值。当缓存达到上限,它应该在写入新数据之前删除最近最少使用的数据用来腾出空闲位置。
方法:为了保持cache的性能,使查找,插入,删除都有较高的性能,我们使用双向链表(std::list)和哈希表(std::unordered_map)作为cache的数据结构,因为:
- 双向链表插入删除效率高(单向链表插入和删除时,还要查找节点的前节点)
- 哈希表保存每个节点的地址,可以基本保证在O(1)时间内查找节点
具体实现细节:
- 越靠近链表头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近访问最少
- 查询或者访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中该节点的地址
- 插入节点时,如果cache的size达到了上限,则删除尾部节点,同时要在hash表中删除对应的项。新节点都插入链表头部。
在下面的实现中,使用的是单链表:
class KeyValue {public: int key, value; KeyValue *next; KeyValue(int key, int value) { next = NULL; this->key = key; this->value = value; } KeyValue() { this->next = NULL; this->key = 0; this->value = 0; }};class LRUCache{private: void moveToTail(KeyValue *prev) { if (prev->next == tail) { return; } KeyValue *node = prev->next; prev->next = node->next; if (node->next != NULL) { hash[node->next->key] = prev; } tail->next = node; node->next = NULL; hash[node->key] = tail; tail = node; }public: unordered_map<int, KeyValue *> hash; KeyValue *head, *tail; int capacity, size; LRUCache(int capacity) { this->head = new KeyValue(0, 0); this->tail = head; this->capacity = capacity; this->size = 0; hash.clear(); } int get(int key) { if (hash.find(key) == hash.end()) { return -1; } moveToTail(hash[key]); return hash[key]->next->value; } void set(int key, int value) { if (hash.find(key) != hash.end()) { hash[key]->next->value = value; moveToTail(hash[key]); } else { KeyValue *node = new KeyValue(key, value); tail->next = node; hash[key] = tail; tail = node; size++; if (size > capacity) { hash.erase(head->next->key); head->next = head->next->next; if (head->next != NULL) { hash[head->next->key] = head; } size--; } } }};
0 0
- LRU 缓存策略
- LRU 缓存策略
- LintCode-LRU缓存策略
- LRU缓存策略
- LRU缓存策略
- lintcode,LRU缓存策略
- LRU缓存策略
- LRU缓存策略设计
- LRU缓存策略设计
- LRU缓存策略-LintCode
- LRU缓存策略
- lintcode LRU缓存策略
- 【链表】实现LRU缓存策略LRU Cache
- 缓存失效策略(fifo lru lfu)
- LRU策略
- 利用LinkedHashMap简单实现基于LRU策略的缓存
- 简单LRU算法实现缓存大小的限制策略
- FIFO、LFU、LRU三种缓存策略之间的区别
- 查看linux版本的三种常用方法
- git 更新某个目录或文件
- Xcode 自定义Log
- 【线性表项目1 - 线性表相关函数1】
- 51单片机学习笔记(六)_串口中断通信+定时器2串口中断
- LRU缓存策略
- 第二周项目三---汉诺塔
- hdu 5437 2015 ACM/ICPC Asia Regional Changchun Online 1002 优先队列
- 第2周项目2-程序的多文件组织
- 面对需求总是被Boss怒改,产品经理该怎么办?
- 25 个 Linux 性能监控工具
- mongodb命令
- ARMv8 與 Linux的新手筆記
- C专家编程