Leetcode -- LRU Cache
来源:互联网 发布:1978年中国经济数据 编辑:程序博客网 时间:2024/05/12 14:12
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.
分析:
这是一个要求设计数据结构的题目,设计的要求是既能快速查找,又能方便移动,因此比较合适的方案是结合链表和哈希表。
在实现时,利用了STL中的list和map,让map指向list中的iterator,从而弥补list不能随机访问的缺点。
struct node{ int val; list<int>::iterator iter; node(int v,list<int>::iterator it) { val = v; iter = it; }};class LRUCache{public: void move2end(int key) { list<int>::iterator it = mp[key]->iter; l.erase(it); l.push_back(key); mp[key]->iter = --l.end(); } LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if(mp.find(key)!=mp.end()) { move2end(key); return mp[key]->val; } else return -1; } void set(int key, int value) { if(mp.find(key)!=mp.end()) { move2end(key); mp[key]->val = value; } else if(mp.size()<capacity) { l.push_back(key); mp[key]=new node(value,--l.end()); } else { int tmp = l.front(); l.pop_front(); mp.erase(tmp); l.push_back(key); mp[key]=new node(value,--l.end()); } } map<int,node*> mp; list<int> l; int capacity;};
0 0
- LeetCode LRU 缓存 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- [LeetCode]LRU Cache
- [LeetCode] LRU Cache
- leetcode LRU Cache
- LeetCode题解:LRU Cache
- LeetCode | LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- LeetCode OJ:LRU Cache
- Leetcode LRU Cache
- LeetCode - LRU Cache
- [Leetcode] LRU Cache (Java)
- Android中的时间自动更新
- 如何初始化基于对话框的MFC程序中对话框的大小
- Malformed OGNL expression: 6578706f7274 [ognl.ParseException: Encountered " <INT_LITERAL> "7274 "" a
- C/C++ SQLite 之基础篇
- Linux解压缩zip,tar,tar.gz,tar.bz2
- Leetcode -- LRU Cache
- LintCode_Remove Linked List Elements
- vim环境搭建:安装vimgdb、使用ctags
- 每日一Vim(2)——简单搜索
- vim命令
- 前端 Leader 是如何带领团队和建设团队文化的
- 普通的用户注册前台验证
- Text实例
- 范型 多个类型的实例 --java编程之范型