class LRUCache {
public:
int capacity = 0;
list<pair<int, int> > cache; // 缓存
unordered_map<int, list<pair<int, int> >::iterator> M;
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if(M.find(key) == M.end()) return -1; // 没有查找到,直接返回 -1
int value = M[key]->second;
cache.erase(M[key]);
cache.push_front({key, value});
M[key] = cache.begin();
return value;
}
void put(int key, int value) {
if(M.find(key) != M.end()) cache.erase(M[key]);
cache.push_front({key, value});
M[key] = cache.begin();
if(cache.size() > this->capacity) {
auto it = cache.rbegin();
M.erase(cache.back().first);
cache.pop_back();
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
【leetcode 设计题(手撸LRU cache) C++】146. LRU Cache
最新推荐文章于 2024-09-11 01:30:06 发布