My simple c++ solution


  • 0
    K
    struct cache{
    int key;
    int val;
    cache(int x, int y):key(x), val(y){};
    };
    class LRUCache{
    private:
    int cap;
    list<cache>mylist;
    unordered_map<int, list<cache>::iterator>table;
    
    void move(int key){
        mylist.erase(table[key]);
        mylist.push_front({key,table[key]->val});
        table[key]=mylist.begin();
    }
    public:
    LRUCache(int capacity) {
        cap=capacity;
    }
    
    int get(int key) {
        if(!table.count(key))return -1;
        move(key);
        return table[key]->val;
    }
    
    void set(int key, int value) {
        if(!table.count(key)){
            cache first(key, value);
            if(mylist.size() >= cap){
                table.erase(mylist.back().key);
                mylist.pop_back();
            }
            mylist.push_front(first);
            table[key]=mylist.begin();
            return;
        }
        table[key]->val=value;
        move(key);
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.