LRU
LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。
struct node
{
node(int _k = 0, int _v = 0, int _cnt=0) :k(_k), v(_v),cnt(_cnt) {}
int k, v, cnt;
};
list<node> myList;
unordered_map<int, list<node>::iterator> myMap;
void LRUset(int key, int val, int k)
{
auto findit = myMap.find(key);
//1.原来的缓存没有,新添加数据
if (findit == myMap.end())
{
//缓存超过限制,删除最少使用的元素
if (myList.size() < k)
{
myMap.erase(myList.rbegin()->k);
myList.pop_back();
}
myList.emplace_front(node(key, val));
myMap[key] = myList.begin();
}
//2.原缓存中存在,把旧数据删除再添加数据
else
{
myList.erase(findit->second);
myList.emplace_front(node(key, val));
myMap[key] = myList.begin();
}
}
int LRUget(int key)
{
auto findit = myMap.find(key);
if (findit == myMap.end())
{
return -1;
}
else
{
//调整使用频率
int val = findit->second->v;
myList.erase(findit->second);
myList.emplace_front(node(key, val));
myMap[key] = myList.begin();
return findit->second->v;
}
}
vector<int> LRU(vector<vector<int> >& operators, int k)
{
vector<int> res;
for (auto& it : operators)
{
if (it[0] == 1)
{
LRUset(it[1], it[2], k);
}
else
{
res.push_back(LRUget(it[1]));
}
}
return res;
}