#pragma once
#include <list>
#include <unordered_map>
using namespace std;
class LRUCache
{
public:
LRUCache(int capacity) : cap(capacity)
{
m.reserve(capacity);
m.max_load_factor(0.75);
}
int get(int key)
{
auto it = m.find(key);
if (it == m.cend())
return -1;
l.splice(l.begin(), l, it->second);
return it->second->second;
}
void put(int key, int value)
{
auto it = m.find(key);
if (it != m.cend())
{
l.erase(it->second);
}
else if (m.size() >= cap)
{
int k = l.rbegin()->first;
l.pop_back();
m.erase(k);
}
l.emplace_front(make_pair(key, value));
m[key] = l.begin();
}
private:
int cap;
list<pair<int, int>> l;
unordered_map<int, list<pair<int, int>>::iterator> m;
};
标签:capacity,int,cap,second,C++,算法,erase,LRU,key
From: https://www.cnblogs.com/txtp/p/17824805.html