#include <list>
#include <unordered_map>
#include <utility>
using namespace std;
class LRUCache
{
private:
int _cap = 0;
list<pair<int, int>> _cache;
unordered_map<int, list<pair<int, int>>::iterator> _map;
public:
int get(int key)
{
if (_map.count(key) > 0)
{
auto temp = *_map[key];
_cache.erase(_map[key]);
_cache.push_front(temp);
_map[key] = _cache.begin();
return temp.second;
}
return -1;
}
void put(int key, int value)
{
if ( _map.count(key) > 0)
{
_cache.erase(_map[key]);
_map.erase(key);
}
else if(_cache.size() == _cap)
{
_cache.pop_back();
_map.erase(key);
}
_cache.push_front(pair<int, int>(key,value));
_map[key] = _cache.begin();
}
};
LRU: C++代码实现
最新推荐文章于 2024-07-20 18:10:49 发布