題意
實現一個LRU cache類,使得在我們需要獲取一個key的值時,如果cache中有,那麼直接返回值,否則就返回-1;同時我們還可以設置一個cache的值,這個主要是在我們出現cache miss的時候,我們需要替換其中的項或者需要從主存中載入對應的項。
思路
LRU,最近最少使用,也就說在出現cache滿的時候,替換原則就是替換最近最少使用的項。類中必須體現出這個原則,那麼我們應該如何來做呢?
首先我們需要一個數據結構來抽象cache結構,用於存儲key和value,自然就需要使用map結構,那麼是使用紅黑樹還是hash table呢,其實都可以。這裏選擇unordered_map
實現
class LRUCache{
public:
LRUCache(int capacity):capacity(capacity) {
}
//獲取一個項,直接從map中通過key查找,是否存在這個鍵,如果沒有,
//那麼說明cache中沒有緩存,直接返回-1.如果找到了,說明cache中有
//這時候還需要完成的工作就是將其在鏈表中的位置移動到最前端。
int get(int key) {
auto it = caches.find(key);
if(it==caches.end())
return -1;
insert(it);
return it->second.first;
}
//set方法就是處理替換的情況,如果已經滿了,那麼就需要替換,如果沒
//有,直接設置對應的項就可以。
void set(int key, int value) {
auto it = caches.find(key);
if(it!=caches.end())
insert(it);
else {
if (caches.size() == capacity) {
caches.erase(recently_use.back());
recently_use.pop_back();
}
recently_use.push_front(key);
}
caches[key] = { value, recently_use.begin() };
}
private:
list<int> recently_use;
unordered_map<int,pair<int,list<int>::iterator>> caches;
void insert(unordered_map<int,pair<int,list<int>::iterator>>::iterator it){
int key = it->first;
list<int>::iterator used_it = it->second.second;
recently_use.erase(used_it);
recently_use.push_front(key);
it->second.second = recently_use.begin();
}
int capacity;
};