leetcode - LRU Cache
2014-09-18 22:55
260 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
key exists in the cache, otherwise return -1.
present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
getand
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.
//根据题目的意思,可以用map<key,value>来查找数据,这里的value,存放的是list<CacheNode>::iterator的迭代器,然后用List来存放value. //这里要求的是如果,一个数据经常被访问到,那么放到这个cache的前面,如果,有一些数据不是经常访问到,那么,再保证这个cache的size的情况下,如果 //Cache的已经满了,就移除不经常访问的数据。 //这个LRUCache支持两种操作,如下: //第一种,get(key),如果,key存在,那么返回value,并且将结点移动到链表的头部,否则,返回-1 //第二种,set(key,value),如果,key存在,那么更新value.并且将结点移动到链表的头部,否则,将结点插入到链表的头部(如果链表的容量达到最大,那么,必须删除最后一个结点,然后再进行insert操作) struct CacheNode //list的结点 { int key; int val; CacheNode(int k, int v):key(k),val(v){}; }; class LRUCache{ public: LRUCache(int capacity) : MaxSize(capacity){ } int get(int key) { std::map<int,std::list<CacheNode>::iterator>::iterator it = mapCache.find(key); if(it != mapCache.end()) { std::list<CacheNode>::iterator it = mapCache[key]; CacheNode node(key,it->val); listCache.erase(it); listCache.push_front(node); mapCache[key] = listCache.begin(); } else { return -1; } return listCache.begin()->val; } void set(int key, int value) { std::map<int,std::list<CacheNode>::iterator>::iterator it = mapCache.find(key); if(it != mapCache.end()) { std::list<CacheNode>::iterator it = mapCache[key]; CacheNode node(key,value); listCache.erase(it); listCache.push_front(node); mapCache[key] = listCache.begin(); } else { if(listCache.size() == MaxSize) { mapCache.erase(listCache.back().key); listCache.pop_back(); } CacheNode node(key,value); listCache.push_front(node); mapCache[key] = listCache.begin(); } } private: int MaxSize; std::list<CacheNode> listCache; std::map<int,std::list<CacheNode>::iterator> mapCache; };
相关文章推荐
- LRU Cache --- LeetCode 面试题
- [LeetCode]LRU Cache
- leetcode -- LRU Cache -- 重点
- 【LeetCode】LRU Cache
- LeetCode --- LRU Cache
- Leetcode#146 LRU Cache
- 【LeetCode】LRU Cache 解题报告
- leetcode: LRU Cache
- LRU Cache (leetcode)
- Leetcode: LRU Cache
- leetcode--LRU Cache
- Java for LeetCode 146 LRU Cache 【HARD】
- 【LeetCode】LRU Cache
- [leetcode] LRU Cache
- leetcode:LRU Cache
- LRU Cache--leetcode
- LeetCode 之 LRU Cache解决思路
- leetcode-LRU Cache
- LeetCode: LRU Cache
- leetcode 日经贴,Cpp code -LRU Cache