您的位置:首页 > 其它

leetcode 146. LRU Cache

2015-01-17 16:25 267 查看
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.

为了查找高效O(1),考虑使用哈希表hash, 为了使插入/删除高效O(1),考虑使用双链表list, 因此采用双链表和哈希表结合。

GET(key):

  hash命中节点node,把node从list中移动到表头,否则返回-1

SET(key, value):

  hash命中node,只需更新hash中的node,并把node从list中移动到表头。

  hash不命中,则需要判断capacity. 如果cache满,需要替换cache中的node,并删除list的表尾元素,cache未满,将node插入表头,更新cache。

struct CacheNode
{
int key;
int value;
CacheNode(int k, int v):key(k), value(v){}
};

class LRUCache{
public:
LRUCache(int capacity)
{
cacheSize = capacity;
}

int get(int key)
{
if (cacheMap.find(key) == cacheMap.end()) // hit fail
return -1;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->value;
}

void set(int key, int value)
{
if (cacheMap.find(key) == cacheMap.end()) // hit fail
{
CacheNode cacheItem(key, value);
if (cacheMap.size() == cacheSize) // cache is full
{
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front(cacheItem);
cacheMap[key] = cacheList.begin();
}
else    // hit success
{
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}

private:
int cacheSize;
unordered_map<int, list<CacheNode>::iterator> cacheMap;
list<CacheNode> cacheList;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: