思路
1.双向链表方便删除操作
2.最近使用的资源更新到表头,表尾自然就是长时间未被使用的资源
3.资源不够的时候删除表尾
代码
#include <iostream>
#include<unordered_map>
using namespace std;
class Node {
public:
int key;
int value;
Node* next;
Node* pre;
Node(int mkey = 0, int mvalue = 0) :key(mkey), value(mvalue), next(nullptr), pre(nullptr) {};
};
class DoubleList
{
private:
Node* head;
Node* tail;
int Size;
public:
DoubleList() :Size(0)
{
head = new Node;
tail = new Node;
head->next = tail;
tail->pre = head;
}
//头部插入
void push_front(Node* node)
{
node->next = head->next;
head->next->pre = node;
head->next = node;
node->pre = head;
Size++;
}
//删除节点
void remove(Node* node)
{
if (Size == 0)
return;
node->pre->next = node->next;
node->next->pre = node->pre;
Size--;
}
//删除尾部节点
Node* pop_tail()
{
if (Size == 0)
return nullptr;
Node* temp = tail->pre; //尾部节点
temp->pre->next = tail;
tail->pre = temp->pre;
Size--;
return temp;
}
};
class LRUCache {
public:
int maxCap;
DoubleList list;
unordered_map<int, Node*> mp;
int curSize;
LRUCache(int capacity) {
maxCap = capacity;
curSize = 0;
}
int get(int key) {
if (mp.count(key))
{
Node* temp = mp[key];
//更新链表中位置
list.remove(temp);
list.push_front(temp);
return mp[key]->value;
}
return -1;
}
void put(int key, int value) {
if (mp.count(key))
{
mp[key]->value = value;
Node* temp = mp[key];
//节点从原来位置断开
list.remove(temp);
list.push_front(temp);
return;
}
Node* newNode = new Node{ key,value };
if (curSize == maxCap)
{
//清除最长时间未用的资源
Node* temp = list.pop_tail();
mp.erase(temp->key);
curSize--;
delete temp;
}
list.push_front(newNode);
mp[key] = newNode;
curSize++;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
int main()
{
LRUCache* obj = new LRUCache(2);
obj->put(2, 1);
obj->put(1, 1);
obj->put(2, 3);
obj->put(4, 1);
obj->get(1);
obj->get(2);
}