leetcode 146. LRU Cache(hash + list)

题目:146. LRU Cache
题意: 实现LRU (最近最少使用) 缓存机制,get方法和set方法
思路:hash用来查找key,list用来存储结点
get:key存在返回,否则返回-1
set:key存在,直接将此结点在list置前;不存在插入list首部,超过容量pop_back
.splice() 用来将list 2中的某个结点插入list 1特定位置
代码:

class LRUCache {
public:
    int cap;
    list<pair<int,int>> cache;
    unordered_map<int, list<pair<int,int>>::iterator> hash;
    LRUCache(int capacity) {
        cap = capacity;
    }

    int get(int key) {
        auto it = hash.find(key);
        if(it == hash.end())
            return -1;
        cache.splice(cache.begin(), cache, it->second);//最近使用,置前
        return it->second->second;
    }

    void put(int key, int value) {
        auto it = hash.find(key);
        if(it != hash.end()){//存在
            it->second->second = value;
            cache.splice(cache.begin(), cache, it->second);//最近使用,置前
        }
        else{
            cache.insert(cache.begin(), make_pair(key, value));
            hash[key] = cache.begin();
            if(cache.size() > cap){
                hash.erase(cache.back().first);//在map中删掉
                cache.pop_back();//在list中删掉
            }
        }
    }
};

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值