LeetCode 146

 

 

class LRUCache {
private:
    int capacity;
    list<pair<int, int>> cache;
    unordered_map<int, list<pair<int, int>> :: iterator> map;
public:
    LRUCache(int capacity) {
        this -> capacity = capacity;
    }
    int get(int key) {
        if(map.find(key) == map.end()) {
            return -1;
        }
        pair<int, int> kv = *map[key];
        cache.erase(map[key]);
        cache.push_front(kv);
        map[key] = cache.begin();
        return kv.second;
    }
    void put(int key, int value) {
        if(map.find(key) == map.end()) {
            if(cache.size() == capacity) {
                map.erase(cache.back().first);
                cache.pop_back();
            }
            cache.push_front(make_pair(key, value));
            map[key] = cache.begin();
        }
        else {
            cache.erase(map[key]);
            cache.push_front(make_pair(key, value));
            map[key] = cache.begin();
        }
    }
};

 

posted @ 2020-05-25 15:18  LightAc  阅读(145)  评论(0编辑  收藏  举报
返回顶端