LeetCode | 146. LRU Cache


题目:

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类,具有push和get的功能,难点在于get的元素每次需要相应提到最前,而push操作需要判断是否当前元素数量超过capacity,若超出则将最近最少访问的元素剔除,压入新的元素,反之则直接压入。


代码:

class LRUCache {
public:
    unordered_map<int, int> um;
    vector<int> q;
    int cap;
    LRUCache(int capacity) {
        um.clear();
        q.clear();
        cap = capacity;
    }
    
    int get(int key) {
        if(um.find(key) != um.end())
        {
            for(int i = 0; i<q.size(); i++)
                if(q[i] == key)
                    q.erase(q.begin()+i);
            q.insert(q.begin(), key);
            return um[key];
        }
        return -1;
    }
    
    void put(int key, int value) {
        if(um.find(key) != um.end())
        {
            um[key] = value;
            for(int i = 0; i<q.size(); i++)
                if(q[i] == key)
                    q.erase(q.begin()+i);
            q.insert(q.begin(), key);
        }
        else
        {
            um.insert(pair<int, int>(key, value));
            if(q.size() < cap)
            {
                q.insert(q.begin(), key);
            }
            else
            {
                q.insert(q.begin(), key);
                um.erase(q[cap]);
                q.erase(q.begin()+cap);
            }
        }
    }
};

不过如代码所示,我的效率真心低(%>_<%,看了一下赞成率高的代码都用到了list类,其中splice功能可以实现LRU的顺序调整。














猜你喜欢

转载自blog.csdn.net/iLOVEJohnny/article/details/80672408