題意:實現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;
};