LRU Cache
原题链接LRU Cache
实现LRU,是一个页面置换算法,当容量满时,将最不常用的那个页删掉,腾出空间容纳新页。
实现的方法是采用map和list作为存储结构,其中
- list保存每个输入的页,本题是键值对\
class LRUCache {
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
if(map_.find(key) == map_.end())
return -1;
else
{
updateLRU(key);
return list_.begin()->second;
}
}
void put(int key, int value) {
auto it = map_.find(key);
if(it != map_.end())
{
it->second->second = value;
updateLRU(key);
}
else
{
if(!list_.empty() && capacity_ == list_.size())
{
map_.erase(list_.back().first);
list_.pop_back();
}
list_.push_front(std::make_pair(key, value));
map_[key] = list_.begin();
}
}
private:
void updateLRU(int key)
{
auto it = map_.find(key);
if(it != map_.end())
list_.splice(list_.begin(), list_, it->second);
}
private:
list<std::pair<int, int>> list_;
unordered_map<int, list<std::pair<int, int>>::iterator> map_;
int capacity_;
};
/**
* 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);
*/