题目需求:1)存入key and value, 可以通过key获得value
可以用hashmap来实现(unordered_map)
2)当capacity不够时,remove掉least recently used
可以用double linked-list来实现(list)
class LRUCache {
public:
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
auto it = hash.find(key);
if(it==hash.end()) return -1;
cache.splice(cache.begin(), cache, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = hash.find(key);
if(it!=hash.end()){
it->second->second = value;
return cache.splice(cache.begin(), cache, it->second);
}
cache.insert(cache.begin(), make_pair(key, value));
hash[key] = cache.begin();
if(cache.size()>size){
hash.erase(cache.back().first);
cache.pop_back();
}
}
private:
unordered_map<int, list<pair<int, int>>::iterator> hash;
list<pair<int, int>> cache;
int size;
};
详细的大家可以看一下reference,感觉没有他讲的好~~~
reference: https://blog.csdn.net/qq508618087/article/details/50995188