LeetCode - LRU Cache
来源:互联网 发布:经济发展数据库 编辑:程序博客网 时间:2024/05/16 04:45
LRU Cache
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.
class LRUCache{ list<pair<int,int> > _cache; unordered_map<int, list<pair<int,int> > :: iterator > _map; int _size;public: LRUCache(int capacity) : _size(capacity) { } int get(int key) { auto itor = _map.find(key); //look up bring the element to front. if(itor == _map.end()) return -1; movetofront(itor->second); return _cache.front().second; } void set(int key, int value) { if(_map.find(key) != _map.end()){ // key exists, update value, bring to front. *_map[key] = make_pair(key,value); movetofront(_map[key]); }else{ //key doesn't exist, if(_map.size() == _size){ // over-write the last node, bring to front. _map.erase(_cache.rbegin()->first); *_cache.rbegin() = make_pair(key,value); movetofront(--_cache.end()); }else _cache.emplace_front(key, value); // insert without copying to front. _map[key] = _cache.begin(); // update key value. } } void movetofront(list<pair<int,int> > :: iterator& it){ if(it != _cache.begin()) _cache.splice(_cache.begin(), _cache, it); }};
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)
- nmon监控linux方法
- sar命令详解
- 关于ContextLoaderListener那点事
- 云计算(二十八)-【HBase】Rowkey设计
- android 如何让appwidget 里面设置TextView 滚动,android widget marquee text
- LeetCode - LRU Cache
- Java中的序列化Serialable高级详解
- 一次关于scan IP 的故障
- 如何查找论文是否被SCI,EI检索
- 堆和栈的区别
- PHP程序员突破成长瓶颈 – 附学习建议
- 了解下PHP的Reflection反射机制
- 算法对应计算机的书籍
- VS2010 修改模板文件,增加默认注释