您的位置:首页 > 其它

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:
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.

//根据题目的意思,可以用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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: