本文参考http://www.cnblogs.com/TenosDoIt/p/3417157.html
为了达到快速有效,本题主要使用了STL中的双向链表List和哈希表undered_map, 其中,对两者需要有较为熟练的应用
代码
</pre><pre class="cpp" name="code">struct LRUNode
{
int key;
int value;
LRUNode(int x, int y):key(x), value(y){}
};
class LRUCache
{
public:
LRUCache(int capacity)
{
size = capacity;
}
int get(int key)
{
if(mapLRU.find(key) == mapLRU.end())
return -1;
else
{
listLRU.splice(listLRU.begin(),listLRU, mapLRU[key]);
mapLRU[key] = listLRU.begin();
return mapLRU[key]->value;
}
}
void set(int key, int value)
{
if(mapLRU.find(key) == mapLRU.end())
{
if(listLRU.size() == size)
{
mapLRU.erase(listLRU.back().key);
listLRU.pop_back();
}
listLRU.push_front(LRUNode(key, value));
mapLRU[key] = listLRU.begin();
}
else
{
mapLRU[key]->value = value;
listLRU.splice(listLRU.begin(), listLRU, mapLRU[key]);
mapLRU[key] = listLRU.begin();
}
}
private:
int size;
list<LRUNode> listLRU;
unordered_map<int, list<LRUNode>::iterator>mapLRU;
};
本文介绍了如何利用STL中的双向链表List和哈希表unordered_map来实现LRU(Least Recently Used)缓存算法。详细解释了结构LRUNode的定义和LRUCache类的get和set方法实现。
990

被折叠的 条评论
为什么被折叠?



