class LRUCache {
public:
LRUCache(int cache_size_) : cache_size(cache_size_) { };
void put(const int &key, const int &val) {
auto it = item_map.find(key); // O(1)
if(it != item_map.end()) {
item_list.erase(it->second);
item_map.erase(it);
}
item_list.push_front(make_pair(key,val));
item_map.insert(make_pair(key, item_list.begin()));
while (item_map.size() > cache_size) {
item_map.erase(item_list.back().first);
item_list.pop_back();
}
};
bool exist(const int &key) {
return (item_map.count(key) > 0);
};
int get(const int &key) {
auto it = item_map.find(key);
item_list.splice(item_list.begin(), item_list, it->second);
return it->second->second; // 注意:list迭代器it在splice之后并未失效;
};
private:
// KV对被保存在list中,方便KV对的位置移动, 最近被使用的KV对被放置在队列前部;
// 为了避免遍历操作,使用map保存key对应的节点在list当中的位置;
list<pair<int, int>> item_list;
size_t cache_size; // LRU Cache大小
unordered_map<int, typename list<pair<int,int>>::iterator> item_map;
};
[C++] LRU实现
最新推荐文章于 2025-02-26 22:33:09 发布