LeetCode ---LRU Cache
2015-07-24 16:14
351 查看
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.
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{ public: LRUCache(int capacity) { m_cache.clear(); m_time2key.clear(); m_key2time.clear(); m_capacity = capacity; m_time = 0; m_size = 0; } int get(int key) { m_time ++; map<int, int >::iterator it = m_cache.find(key); if(it != m_cache.end() ) { m_time2key.erase(m_key2time[key]); m_time2key.insert(std::make_pair(m_time, key)); m_key2time[key] = m_time; return m_cache[key]; } return -1; } void set(int key, int value) { m_time++; map<int, int >::iterator it = m_cache.find(key); if(it != m_cache.end()) { m_cache[key] = value; m_time2key.insert(std::make_pair(m_time, key)); m_time2key.erase(m_key2time[key]); m_key2time[key] = m_time; } else { if(m_size == m_capacity) { map<long long, int>::iterator it = m_time2key.begin(); m_cache.erase(it->second); m_time2key.erase(it->first); m_key2time.erase(it->second); m_size--; } m_cache.insert(std::make_pair(key, value)); m_time2key.insert(std::make_pair(m_time, key)); m_key2time.insert(std::make_pair(key, m_time)); m_size++; } } private: map<int, int > m_cache; long long m_time; map<long long, int> m_time2key; map<int, long long> m_key2time; int m_capacity; int m_size; };
相关文章推荐
- 104-LRU Cache
- LRU Cache
- LruCache
- 页面偶尔出现查询/页面刷新错误,ejs出现类型报错/方法报错
- LRU cache实现
- Android中Bitmap的加载和Cache(三级缓存 :LruCache,DiskLruCache)学习笔记
- LRU算法–缓存淘汰算法
- LinkedHashMap详解及其在LruCache中的应用
- Android Studio 快捷键
- 使用Scala开发Apache Kafka应用入门
- Vim快捷键大全
- 网络栈加载完数据发送消息时的堆栈
- jvm内存使用上限
- std::function
- HDU 2824 The Euler function(欧拉函数)
- HDU 3501 Calculation 2(欧拉函数)
- 通过Handler与线程嵌套TimerTask实现循环交替任务
- JAVASCRIPT实现翻页保存已勾选的项目
- 通过Handler与线程嵌套TimerTask实现循环交替任务 分类: Android 2015-07-24 16:14 162人阅读 评论(0) 收藏
- UVA 10869 - Brownie Points II(树阵)