标签:
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.
实现一个LRU的缓存,这实际上就是操作系统中内存管理的一种算法。最不经常使用算法,要求当内存使用完时先淘汰掉最久未使用的内存,这里模拟了两个对内存的操作,get和set。
因为要存储key和value,所以很明显需要使用一个map,但是map无法记录key的使用顺序,所以还需要一个能记录使用顺序的数据结构,这里可以使用vector和list,由于set操作是当key已经存在时替换当前的value,所以记录顺序的数据结构可能会有频繁的删除操作,那么需要舍弃掉vector,最后记录使用顺序的数据结构就需要使用list。
下面再分析get和set需要处理的事情:
get操作时,需要执行下面两步操作:
class LRUCache{
private:
int capacity;
map<int,int> datas;
list<int> s;
public:
LRUCache(int capacity) {
this->capacity=capacity;
}
int get(int key) {
auto iter=datas.find(key);
if(iter!=datas.end())
{
update(iter);
return iter->second;
}
else
return -1;
}
void set(int key, int value) {
int length=datas.size();
auto iter=datas.find(key);
if(iter!=datas.end())
{
datas[key]=value;
update(iter);
}
else
{
if(length>=capacity)
{
datas.erase(s.back());
s.pop_back();
}
s.push_front(key);
datas[key]=value;
}
}
private:
void update(map<int,int>::iterator iter)
{
int key=iter->first;
s.remove(key);
s.push_front(key);
}
};class LRUCache{
private:
typedef pair<int,list<int>::iterator> PILI;
int capacity;
map<int,PILI> datas;
list<int> s;
public:
LRUCache(int capacity) {
this->capacity=capacity;
}
int get(int key) {
auto iter=datas.find(key);
if(iter!=datas.end())
{
update(iter);
return iter->second.first;
}
else
return -1;
}
void set(int key, int value) {
int length=datas.size();
auto iter=datas.find(key);
if(iter!=datas.end())
{
iter->second.first=value;
update(iter);
}
else
{
if(length>=capacity)
{
datas.erase(s.back());
s.pop_back();
}
s.push_front(key);
datas[key]=PILI(value,s.begin());
}
}
private:
void update(map<int,PILI>::iterator iter)
{
int key=iter->first;
s.erase(iter->second.second);
s.push_front(key);
iter->second.second=s.begin();
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/47204511