程式語言 - LeetCode - C++ - 146. LRU Cache



題目:


解答:

class LRUCache {
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
        if (q.find(key) == q.end()) {
            return -1;
        }

        auto it = q[key];
        int val = it->second;
        cache.erase(it);
        cache.push_front({key, val});
        q[key] = cache.begin();

        return val;
    }
    
    void put(int key, int value) {
        if (q.find(key) != q.end()) {
            cache.erase(q[key]);
        }
        else if (cache.size() == capacity) {
            auto last = cache.back();
            q.erase(last.first);
            cache.pop_back();
        }

        cache.push_front({key, value});
        q[key] = cache.begin();
    }

private:
    int capacity;
    list<pair<int, int>> cache;
    unordered_map<int, list<pair<int, int>>::iterator> q;
};

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