LRU Cache

    0

    0

    Mansimar Anand

    LRU cache code

    class DS {
    public:
        int value;
        list<int>::iterator itr;
    };
    class LRUCache {
    public:
        int capacity;
        list<int> Queue;
        unordered_map<int, DS> HashMap;
        LRUCache(int capacity) {
            this->capacity = capacity;
        }
        int get(int key) {
            if(!HashMap.count(key)) {
                return -1;
            }
            int value = HashMap[key].value;
            put(key, value);
            return value;
        }
        void put(int key, int value) {
            if(HashMap.count(key)) {
                Queue.erase(HashMap[key].itr);
                HashMap.erase(key);
            }
            if(Queue.size() == capacity) {
                HashMap.erase(Queue.back());
                Queue.pop_back();
            }
            Queue.push_front(key);
            HashMap[key] = {value, Queue.begin()};
        }
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.