LRU-Cache
2019-07-25 本文已影响0人
DaiMorph
class LRUCache {
private:
struct CacheNode {
int key, value;
CacheNode(int k, int v) :key(k), value(v) {}
};
int capacity;
unordered_map<int, list<CacheNode>::iterator>cacheMap;
list<CacheNode>cachelist;
public:
LRUCache(int capacity) {
this->capacity = 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 cacheMap[key]->value;
}
void set(int key, int value)
{
if (cacheMap.find(key) == cacheMap.end()) {
if (cachelist.size() == capacity)
{
cacheMap.erase(cachelist.back().key);
cachelist.pop_back();
}
cachelist.push_front(CacheNode{ key,value });
cacheMap[key] = cachelist.begin();
}
else {
cacheMap[key]->value = value;
cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]);
cacheMap[key] = cachelist.begin();
}
}
};