146. LRU Cache
来源:互联网 发布:seo资源网 编辑:程序博客网 时间:2024/04/30 19:10
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(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.
LRU缓存的实现。在这种方法中,如果写入内存的时候容量不足了,最近没用的那一块内存将被换出,以存入新的数据。这里用unordered_map和list来实现。在链表中,最近用过的点在头部,最近没用过的点在尾部,哈希映射表用来保存键值和节点的对应关系。在get函数中,如果在映射表中找不到key对应的那一个节点,返回1;如果找到了,将该节点移到链表的头部(做法是复制和删除原来的点,将复制得到的点插在头部),表示最新用过这个点。在set函数中,如果在映射表中找不到key对应的那一个节点,则要插入该节点,因为是最近用过的,所以查到头部,注意如果链表长度到达最大值,要把最后的节点删除;如果找到了,则更新这个点的实值,然后将该点移到头部(做法和上面的一样)。这样就简单实现了这种缓存机制。
代码:
class LRUCache{public: LRUCache(int capacity):Max(capacity){ } int get(int key) { auto it=um.find(key); if(it==um.end()) return -1; auto lit=it->second; node newnode(lit->key,lit->val); ls.erase(lit); ls.push_front(newnode); um[key]=ls.begin(); return ls.begin()->val; } void set(int key, int val) {auto it=um.find(key); if(it==um.end()) { if(ls.size()==Max) { um.erase(ls.back().key); ls.pop_back();}ls.push_front(node(key,val));um[key]=ls.begin();}else{auto lit=it->second;node newnode(key,val);ls.erase(lit);ls.push_front(newnode);um[key]=ls.begin();} } private:struct node{int key;int val;node(int k,int v):key(k),val(v){}};list<node>ls;unordered_map<int,list<node>::iterator>um;int Max;};
- LeetCode 146. LRU Cache
- [leetcode] 146.LRU Cache
- 146. LRU Cache
- leetcode 146. LRU Cache
- Leetcode 146. LRU Cache
- Leetcode - 146. LRU Cache
- Leetcode 146. LRU Cache
- [leetcode] 146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode 146. LRU Cache
- LeetCode-146. LRU Cache
- LeetCode 146. LRU Cache
- 146. LRU Cache
- LeetCode 146. LRU Cache
- 146. LRU Cache
- 146. LRU Cache
- 146. LRU Cache
- 146. LRU Cache
- cmd习惯颜色
- Android组件式开发(2)——实现网格布局的RadioButton矩阵
- LightOJ 1019 Brush (V) 最短路裸题
- android developer tiny share-20160908
- SQL Server 取日期时间部分
- 146. LRU Cache
- Linux内核源代码分析——Linux内核的入口
- java中的继承(向上转型)
- win10 vs2015 php源码编译
- iOS中保证线程安全的几种方式与性能对比
- 自定义控件三部曲之动画篇(十二)——animateLayoutChanges与LayoutTransition
- HTTP 缓存策略
- Android xml资源文件中@、@android:type、@*、?、@+含义和区别
- Logstash 日志搜集处理框架 安装配置