LRU机制

使用双向链表(数据类型为pair<int,int>,实际就是Key,value)+哈希表(哈希表的第一项为key,第二项为list的迭代器

效果图
class LRUCache {
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
       auto it = helper.find(key);
       if(it==helper.end()) return -1;
       auto it2 = it->second;
       int temp1 = it2->first;
       int temp2 = it2->second;
       a.erase(it2);
       a.push_front(make_pair(temp1,temp2));
       helper[key] = a.begin();
       return temp2;
    }
    
    void put(int key, int value) {
        auto it = helper.find(key);
        if(it!=helper.end()){
            auto it2 = it->second;
            it2->second = value;
            auto temp = make_pair(it2->first,it2->second);
            a.erase(it2);
            a.push_front(temp);
            helper[key] = a.begin();
        }
        else{
            if(a.size()==capacity){
                auto it2 = a.rbegin();
                helper.erase(it2->first);
                a.pop_back();
                a.push_front(make_pair(key,value));
                helper[key] = a.begin();
            }
            else{
                a.push_front(make_pair(key,value));
                helper[key] = a.begin();
            }
        }
    }
private:
    int capacity;
    list<pair<int,int>> a;
    unordered_map<int,list<pair<int,int>>::iterator> helper;
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容