zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    软件工程第四次作业
    软件工程第三次作业
    图片
    软件工程第二次作业
    软件工程第一次作业
    我的大学生活-3-35-任延勇
    我的未来只有我知道
    cpu占用率高排查知识点
    LeetCode字符串题目
    hashmap
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281217.html
Copyright © 2011-2022 走看看