每天一道LeetCode-----实现LRU置换算法

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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值