LeetCode 146 LRU Cache(list+unordered_map实现LRU缓存算法)

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
题目大意:实现LRU(最近最少使用)算法。要求实现get和put两个操作。get(key)取出缓存中与key对应的value,如果key不在缓存中,返回-1。put(key, value)将一个key-value数据对保存到缓存中,如果缓存已经满了,那么就先将最近最少使用的key-vaule对从缓存中删除,再把新数据对插入到缓存中。题目要求尽量在O(1)的时间复杂度内实现get和put操作。

解题思路:首先,最直观的想法就是用STL中的list(双向链表)保存缓存中的key,表头节点表示最近操作的数据,表尾节点表示当前缓存中最少使用的数据,再利用map保存key-value。每次put操作时先用find函数在list中查找key,如果存在则将key换到list的表头;不存在就检查list是否已经满了,如果list已满就把表尾节点删除再在表头插入新节点,否则直接在表头插入新节点。get操作和put类似,这里就不多说了。

代码如下:

class LRUCache {
public:
    LRUCache(int capacity) {
        lt.resize(capacity, -1);
        sz = capacity;
    }
    int get(int key) {
        if(ump[key]){
            auto it = find(lt.begin(), lt.end(), key);
            lt.erase(it);
            lt.push_front(key);
        }
        return ump[key] == 0 ? -1 : ump[key];
    }
    
    void put(int key, int value) {
        if(ump[key]){//存在缓存
            auto it = find(lt.begin(), lt.end(), key);
            lt.erase(it);
            lt.push_front(key);
        }else{//不存在缓存
            if(lt.size() == sz){
                auto it = lt.end();
                ump[*(--it)] = 0;
                lt.erase(it);
            }
            lt.push_front(key);
        }
        ump[key] = value;
    }
private:
    list lt;
    unordered_map ump;
    size_t sz;
};
上面的方法比较容易想到,但是缺点也很明显,就是非常慢,18个test case跑了大概238ms。通过学习别人的代码,我发现有一种比较巧妙的数据存储方式,可以显著地降低时间复杂度。当然还是用list和map,只不过list里面存的是pair,而map里面存的是>::iterator>,第二个元素是一个list>类型的迭代器,它指明了key在list中的位置,这样我们就不需要使用find函数来寻找key,这种做法的确能够降低时间复杂度,改进后的代码只跑了88ms,相对来说还是一个比较大的提升。

改进后的代码:

class LRUCache {
public:
    LRUCache(int capacity) {
        lt.resize(capacity, make_pair(-1, -1));
        sz = capacity;
    }
    int get(int key) {
        auto tmp = ump.find(key);
        if(tmp != ump.end() && tmp->second != lt.end()){
            pair p = make_pair(tmp->second->first, tmp->second->second);
            lt.erase(tmp->second);
            lt.push_front(p);
            return p.second;
        }
        return -1;
    }
    
    void put(int key, int value) {
        auto tmp = ump.find(key);
        if(tmp != ump.end() && tmp->second != lt.end()){//存在缓存
            lt.erase(tmp->second);
        }
        
            if(lt.size() == sz){
                ump[lt.back().first] = lt.end();
                lt.pop_back();
            }
        
        lt.emplace_front(make_pair(key, value));
        ump[key] = lt.begin();
    }
private:
    list> lt;
    unordered_map>::iterator> ump;
    size_t sz;
};


你可能感兴趣的:(模拟)