LRU Cache
来源:互联网 发布:创建wifi热点软件 编辑:程序博客网 时间:2024/06/02 00:58
参考:http://fisherlei.blogspot.tw/2013/11/leetcode-lru-cache-solution.html
实现一个LRU的缓存。当要插入一个新的数值时,缓存的存储的个数超过预定的大小时,将之前访问最少的元素移出缓存。
实现方法:用一个双向链表来存储真实的value值,用一个hash map来保存key和它对应的value在双向链表的地址。
每次访问key对应的value时,就把这个value移到链表的头部。当要插入一个新值时,如果空间大小超出了预定的大小时,
则删除链表尾部的值,再将新值插入链表的头部。
#include <map>#include <cstdio>#include <iostream>#include <unordered_map>#include <list>using namespace std;struct CacheItem {public:int key;int value;CacheItem(int k, int v): key(k), value(v) {}};class LRUCache{public: LRUCache(int capacity) {m_capacity = capacity; } int get(int key) { if(m_map.find(key) == m_map.end()) return -1; moveToHead(key); return m_map[key]->value; } void set(int key, int value) {if(m_map.find(key) == m_map.end()) {CacheItem item(key, value);if(LRU_cache.size() >= m_capacity) {m_map.erase(LRU_cache.back().key);LRU_cache.pop_back();}LRU_cache.push_front(item);m_map[key] = LRU_cache.begin();return;}m_map[key]->value = value;moveToHead(key); }private: unordered_map<int, list<CacheItem>::iterator> m_map;list<CacheItem> LRU_cache;int m_capacity; void moveToHead(int key) {CacheItem item = *m_map[key];LRU_cache.erase(m_map[key]);LRU_cache.push_front(item);m_map[key] = LRU_cache.begin();}};
0 0
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- lru cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU cache
- LRU Cache
- LRU Cache
- LRU Cache
- LRU Cache
- 2014-11-04 Java
- 对数的发展史
- java中CountDownLatch线程同步的入门使用
- 关于 Fragment 之3___fragment在xml布局中写法
- Intel Galileo笔记(七)小小的玩耍之超声波测距
- LRU Cache
- 一个jquery对table的操作
- eclipse设置自定义快捷键和导入快捷键文件
- 黑马程序员——其他3:jar包
- Android API学习之画布Canvas、颜料Paint
- sql语句优化
- hashset将list去重并拼接成字符串
- Mysql 关键字-保留字
- hdoj 2050 折线分割平面 【几何模板】