LRU-Cache

作者: DaiMorph | 来源:发表于2019-07-25 00:23 被阅读0次
class LRUCache {
private:
    struct CacheNode {
        int key, value;
        CacheNode(int k, int v) :key(k), value(v) {}
    };
    int capacity;
    unordered_map<int, list<CacheNode>::iterator>cacheMap;
    list<CacheNode>cachelist;
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    int get(int key)
    {
        if (cacheMap.find(key) == cacheMap.end())return -1;
        cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]);
        cacheMap[key] = cachelist.begin();
        return cacheMap[key]->value;
    }
    void set(int key, int value)
    {
        if (cacheMap.find(key) == cacheMap.end()) {
            if (cachelist.size() == capacity)
            {
                cacheMap.erase(cachelist.back().key);
                cachelist.pop_back();
            }
            cachelist.push_front(CacheNode{ key,value });
            cacheMap[key] = cachelist.begin();
        }
        else {
            cacheMap[key]->value = value;
            cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]);
            cacheMap[key] = cachelist.begin();
        }
    }
};

相关文章

网友评论

      本文标题:LRU-Cache

      本文链接:https://www.haomeiwen.com/subject/pvzzlctx.html