LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。
#include <unordered_map>
#inlcude <list>
#include <algorithm>
#include <iostream>
using namespace std;
struct Node
{
int key;
int value;
};
class LRUCache{
private:
int maxSize ;
list<Node> cacheList;
unordered_map<int, list<Node>::iterator > mp;
public:
LRUCache(int capacity) {
maxSize = capacity;
}
int get(int key) {
unordered_map<int, list<Node>::iterator >::iterator it = mp.find(key);
if(it==mp.end()) //没有命中
{
return -1;
}
else //在cache中命中了
{
list<Node>::iterator listIt = mp[key];
Node newNode;
newNode.key = key;
newNode.value = listIt->value;
cacheList.erase(listIt); //先删除命中的节点
cacheList.push_front(newNode); //将命中的节点放到链表头部
mp[key] = cacheList.begin();
}
return cacheList.begin()->value;
}
void set(int key, int value) {
unordered_map<int, list<Node>::iterator >::iterator it = mp.find(key);
if(it==mp.end()) //没有命中
{
if(cacheList.size()==maxSize) //cache满了
{
mp.erase(cacheList.back().key);
cacheList.pop_back();
}
Node newNode;
newNode.key = key;
newNode.value = value;
cacheList.push_front(newNode);
mp[key] = cacheList.begin();
}
else //命中
{
list<Node>::iterator listIt = mp[key];
cacheList.erase(listIt); //先删除命中的节点
Node newNode;
newNode.key = key;
newNode.value = value;
cacheList.push_front(newNode); //将命中的节点放到链表头部
mp[key] = cacheList.begin();
}
}
};