タイトル:https : //leetcode-cn.com/problems/lru-cache/
リファレンス:https : //leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he- shi-xian-by-labuladong /
使用しているデータ構造を使用して、LRU(最近使用されていない)キャッシュメカニズムを設計および実装します。次の操作をサポートする必要があります。
Get data get(key)-キー(key)がキャッシュに存在する場合は、キーの値を取得し(常に正の数)、それ以外の場合は-1を返します。
書き込みデータの書き込み(キー、値)-キーが存在しない場合は、そのデータ値を書き込みます。キャッシュ容量が上限に達すると、新しいデータを書き込む前に、最も最近使用されていないデータ値を削除して、新しいデータ値のための余地を残す必要があります。
解決策:unordered_map +二重リンクリスト、Oおよび1を達成するためのgetおよびput操作。
class LRUCache {
public:
int cap;
list<pair<int,int> > li;
unordered_map<int,list<pair<int,int> >::iterator> mp;
LRUCache(int capacity) {
cap = capacity;
li.clear();
mp.clear();
}
int get(int key) {
auto it = mp.find(key);
if(it == mp.end()) return -1;
pair<int,int> p = *mp[key];
li.erase(mp[key]);//删除数据
li.push_front(p);//更新链表
mp[key] = li.begin();//更新map
return p.second;
}
void put(int key, int value) {
auto it = mp.find(key);
if(it == mp.end()) {//原key不存在
if(li.size() == cap) {//满容器删back()
mp.erase(mp.find(li.back().first));
li.pop_back();
}
//加入数据,更新list/map
li.push_front(make_pair(key,value));
mp[key] = li.begin();
}else {//key存在
pair<int,int> p = *mp[key];
p.second = value;
li.erase(mp[key]);//删除数据
li.push_front(p);//更新链表
mp[key] = li.begin();//更新map
}
}
};
/**
* 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);
*/