LeetCode "LRU Cache"

1A. It is a design problem actually. It tests your ability to connect your knowledge of data structures & algorithms, with real world problems.

class LRUCache{
private:
    deque<int> q; // by key
    unordered_map<int, int> hash;
    int _capacity;
public:
    LRUCache(int capacity) {
        _capacity = capacity;
    }
    
    int get(int key) {
        if (hash.find(key) != hash.end())
        {
            //    Update queue
            auto it = std::find(q.begin(), q.end(), key);
            q.erase(it);
            q.push_back(key);
            //
            return hash[key];
        }
        return -1;
    }
    
    void set(int key, int value) {
        if (hash.find(key) != hash.end())
        {
            //    Update queue
            auto it = std::find(q.begin(), q.end(), key);
            q.erase(it);
            q.push_back(key);
        }
        else
        {
            if(q.size() < _capacity)
            {
                q.push_back(key);
            }
            else
            {
                //    Invalidate LRU
                int okey = q.front();
                q.pop_front();
                hash.erase(okey);
                q.push_back(key);
            }
        }
        hash[key] = value;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3911655.html