leetcode LRU Cache

2014-11-24 02:34:54 · 作者: · 浏览: 1
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.
I wrote a wrong code like this :
[cpp]
class LRUCache {
public:
int size;
list cacheList;
unordered_map::iterator> cacheMap;
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
if (cacheMap.find(key) == cacheMap.end())
return -1;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return *(cacheList.begin());
}
void set(int key, int value) {
if (cacheMap.find(key) == cacheMap.end()) {
cacheList.push_front(value);
cacheMap.insert(make_pair(key, cacheList.begin()));
if (cacheList.size() > size) {
//cacheMap.erase(cacheList.back());
cacheList.pop_back();
}
}
else {
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
*(cacheList.begin()) = value;
cacheMap[key] = cacheList.begin();
}
}
};
Some comments:
1. Erase needs the parameters iterator or key, so list isn't enough. Some nodes are still in map but not in list, so Runtime error.
2.
[cpp]
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
3. front(), back() return value_types, but begin() and end() return iterators.
Right Code:
[cpp]
class CacheNode {
public:
int key, value;
CacheNode(int key, int value):key(key), value(value) {}
};
class LRUCache {
public:
int size;
list cacheList;
unordered_map::iterator> cacheMap;
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
if (cacheMap.find(key) == cacheMap.end())
return -1;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheList.begin()->value;
}
void set(int key, int value) {
if (cacheMap.find(key) == cacheMap.end()) {
cacheList.push_front(CacheNode(key,value));
cacheMap.insert(make_pair(key, cacheList.begin()));
if (cacheList.size() > size) {
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
}
else {
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheList.begin()->value = value;
cacheMap[key] = cacheList.begin();
}
}
};