您的位置:首页 > 其它

leetcode LRU Cache

2014-11-24 00:29 411 查看
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.

class LRUCache{
private:
list<pair<int,int> > keyList;
unordered_map<int, list<pair<int,int> >::iterator> cacheTable;
int capacity;
void updateCache(int key,int value){
keyList.erase(cacheTable[key]);
cacheTable[key] = keyList.insert(keyList.end(), make_pair(key,value));
}
public:
LRUCache(int capacity) {
this->capacity = capacity;
}

int get(int key) {
if(cacheTable.find(key) == cacheTable.end()){
return -1;
}else{
updateCache(key, cacheTable[key]->second);
return cacheTable[key]->second;
}
}

void set(int key, int value) {
if(cacheTable.find(key) != cacheTable.end()){
updateCache(key, value);
}else{
if(capacity <= 0){
cacheTable.erase(keyList.front().first);
keyList.pop_front();
}else{
capacity--;
}
cacheTable[key] = keyList.insert(keyList.end(), make_pair(key,value));
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: