题意:实现LRU(最近最久未用),包括get和set操作。
//使用一个双向链表存储数据(地址和内容),数据的顺序表示了它们被访问的时间顺序,越靠后访问时间越早
//使用Map存储地址(key)对应的链表中数据的地址,加快数据的查找速度
//get操作:只需向Map中查找是否有对应项即可,存在则将双向链表中的数据删除,并在链表前端重新插入
//set操作:先在Map中查找是否有对应项,如果有,则将链表中的项直接删除再插入,如果没有直接向链表头插入数据
//插入完成需要检测元素个数是否超过了缓存容量,超过了则将链表尾部删除
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
map<int, list<node>::iterator>::iterator it = memMap.find(key);
int retVal = -1;
if(it != memMap.end())
{
node nt = *(it->second);
retVal = nt.value;
memList.erase(it->second);
memList.push_front(nt);
memMap[key] = memList.begin();
}
return retVal;
}
void put(int key, int val) {
map<int, list<node>::iterator>::iterator it = memMap.find(key);
node nt(key, val);
if(it != memMap.end())
{
memList.erase(it->second);
}
memList.push_front(nt);
memMap[key] = memList.begin();
if(memList.size()>this->capacity)
{
int dkey = memList.back().address;
memList.pop_back();
memMap.erase(dkey);
}
}
private:
struct node
{
int address;
int value;
node(int add, int val)
{
address = add;
value = val;
}
};
unsigned int capacity;
list<node> memList;
map<int, list<node>::iterator> memMap;
};