• leetcode[146]LRU Cache


    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

    struct CacheNode
    {
        int key;
        int value;
        CacheNode(int k,int v):key(k),value(v){}
    };
    class LRUCache{
    public:
        LRUCache(int capacity) {
            size=capacity;
        }
        
        int get(int key) {
            if(lmap.count(key))
            {
                auto iter=lmap[key];
                lis.splice(lis.begin(),lis,iter);
                lmap[key]=lis.begin();
                return lis.begin()->value;
            }
            else
                return -1;
        }
        
        void set(int key, int value) {
            if(lmap.count(key))
            {
                auto iter=lmap[key];
                lis.splice(lis.begin(),lis,iter);
                lis.begin()->value=value;
                lmap[key]=lis.begin();
                return;
            }
            else
            {
                if(lis.size()==size)
                {
                   lmap.erase(lis.back().key);
                   lis.pop_back();
                   lis.push_front(CacheNode(key,value));
                   lmap[key]=lis.begin();
                }
                else
                {
                    lis.push_front(CacheNode(key,value));
                    lmap[key]=lis.begin();
                }
                return;
            }
        }
    private:
        int size;
        list<CacheNode> lis;
        unordered_map<int,list<CacheNode>::iterator> lmap;
    };
  • 相关阅读:
    用Creator实现一个擀面的效果
    游戏开发中的多语言处理
    Docker(六)容器数据卷
    Docker(五)Docker镜像讲解
    Docker(四)Docker镜像安装
    Docker(三)Docker常用命令
    Docker(二)Docker配置
    nginx 与 tomcat 组合搭建web服务
    Zookeeper 使用
    tomcat-manager 设置
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281217.html
Copyright © 2020-2023  润新知