您的位置:首页 > 其它

leetcode LRU Cache

2014-07-31 14:26 330 查看
本文参考/article/4879634.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;

};



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: