leetcode 146 LRU cache mechanism

topic

Use your disposal data structures, design and implement an LRU (least recently used) cache mechanism. It should support the following: Obtain the data and write data to get put.
Get data get (key) - If the key (key) is present in the cache, the acquisition value of the key (always positive), otherwise -1.
Write data put (key, value) - If the key is not present, the value of the data which is written. When the cache capacity limit is reached, it should delete the least recently used data values before writing new data to make room for new data value.
Advanced:
If you can do both operations in O (1) time complexity?
 

C ++ code

class LRUCache {
public:
    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
        auto it = map1.find(key);
        if(it == map1.end())
            return -1;
        list1.splice(list1.begin(), list1, it->second);
        return it->second->second;
    }
    
    void put(int key, int value) {
        auto it = map1.find(key);
        if(it != map1.end())
        {
            list1.erase(it->second);
        }
        if(list1.size() == cap)
        {
            int k = list1.rbegin()->first;
            list1.pop_back();
            map1.erase(k);
        }
        list1.push_front(make_pair(key, value));
        map1[key] = list1.begin();
    }
private:
    int cap;
    list<pair<int, int>> list1;
    unordered_map<int, list<pair<int, int>>::iterator> map1;
};

/**
 * 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);
 */

 

Guess you like

Origin www.cnblogs.com/xumaomao/p/11359692.html