![](https://img2020.cnblogs.com/blog/1505779/202005/1505779-20200525151741129-1565088549.png)
class LRUCache {
private:
int capacity;
list<pair<int, int>> cache;
unordered_map<int, list<pair<int, int>> :: iterator> map;
public:
LRUCache(int capacity) {
this -> capacity = capacity;
}
int get(int key) {
if(map.find(key) == map.end()) {
return -1;
}
pair<int, int> kv = *map[key];
cache.erase(map[key]);
cache.push_front(kv);
map[key] = cache.begin();
return kv.second;
}
void put(int key, int value) {
if(map.find(key) == map.end()) {
if(cache.size() == capacity) {
map.erase(cache.back().first);
cache.pop_back();
}
cache.push_front(make_pair(key, value));
map[key] = cache.begin();
}
else {
cache.erase(map[key]);
cache.push_front(make_pair(key, value));
map[key] = cache.begin();
}
}
};
作者:LightAc
出处:https://www.cnblogs.com/lightac/
联系:
Email: dzz@stu.ouc.edu.cn
QQ: 1171613053
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。