Leetcode 146. LRU缓存机制

cnt辐射que中key出现的次数,当次数=0时,代表key被移出

class LRUCache {
public:
    int cap;
    unordered_map<int, int> cnt, val;
    deque<int> que;
    LRUCache(int capacity) {
        cap = capacity;
    }
    int get(int key) {
        if (!cnt.count(key)) return -1;
        ++cnt[key], que.push_back(key);
        return val[key];
    }
    void put(int key, int value) {
        val[key] = value, que.push_back(key);
        if (!cnt.count(key)) cnt[key] = 1;
        else  ++cnt[key];
        while (cnt.size() > cap) {
            auto x = que.front(); que.pop_front();
            if (!--cnt[x]) cnt.erase(x), val.erase(x);
        }
    }
};

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

你可能感兴趣的:(Leetcode 146. LRU缓存机制)