您的位置:首页 > 其它

leetcode: LRU Cache

2014-06-30 12:32 337 查看
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.

网上找到的,自认为最优的解法,用一个unordered_map来保存key和对应list的迭代器,list保存key, value

要求对stl容器的成员函数很熟悉list.splice( iterator & pos, list, iterator &iter)

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

int get(int key) {
if( cache.count( key)){
auto iter = cache[key];
cacheList.splice( cacheList.begin(), cacheList, iter);
cache[key] = cacheList.begin();
return cacheList.begin()->value;
}
else
return -1;
}

void set(int key, int value) {
if( cache.count( key)){
auto iter = cache[key];
cacheList.splice( cacheList.begin(), cacheList, iter);
cache[key] = cacheList.begin();
cacheList.begin()->value = value;
}
else{
if( cache.size() >= cap){
cache.erase( cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front( cacheNode( key, value));
cache[key] = cacheList.begin();
}
}
private:
struct cacheNode{
int key;
int value;
cacheNode( int k, int v): key(k), value(v){}
};
int cap;
list< cacheNode> cacheList;
unordered_map< int, list< cacheNode>::iterator> cache;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: