LRU cache mechanism (hash linked list)

Title: https://leetcode-cn.com/problems/lru-cache/
Reference: https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he- shi-xian-by-labuladong /
Design and implement an LRU (least recently used) caching mechanism using the data structures you have. It should support the following operations: Get data get and write data put.

Get data get (key)-If the key (key) exists in the cache, get the value of the key (always a positive number), otherwise return -1.
Write data put (key, value)-If the key does not exist, write its data value. When the cache capacity reaches the upper limit, it should delete the least recently used data value before writing new data, thereby leaving room for the new data value.
Solution: unordered_map + doubly linked list, get and put operations to achieve O (1).

class LRUCache {
public:
    int cap;
    list<pair<int,int> > li;
    unordered_map<int,list<pair<int,int> >::iterator> mp;
    
    LRUCache(int capacity) {
        cap = capacity;
        li.clear();
        mp.clear();
    }
    
    int get(int key) {
        auto it = mp.find(key);
        if(it == mp.end()) return -1;
        pair<int,int> p = *mp[key];
        li.erase(mp[key]);//删除数据
        li.push_front(p);//更新链表
        mp[key] = li.begin();//更新map
        return p.second;
    }
    
    void put(int key, int value) {
        auto it = mp.find(key);
        if(it == mp.end()) {//原key不存在
            if(li.size() == cap) {//满容器删back()
                mp.erase(mp.find(li.back().first));
                li.pop_back();
            }
            //加入数据,更新list/map
            li.push_front(make_pair(key,value));
            mp[key] = li.begin();
        }else {//key存在
            pair<int,int> p = *mp[key];
            p.second = value;
            li.erase(mp[key]);//删除数据
            li.push_front(p);//更新链表
            mp[key] = li.begin();//更新map
        }
    }
};


/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
Published 152 original articles · won praise 2 · Views 6457

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104634642