leetcode 146. LRU Cache

题目

手写一个LRU cache

思路和代码

用stl
注意到 list<int> begin()end()iterator类型的
front()back()int类型的
还应该注意到erase写法

class LRUCache {
public:
    LRUCache(int capacity) {
        cap = capacity;
    }

    int get(int key) {
        auto it = cache.find(key);
        if(it == cache.end())
            return -1;
        // found it and swap to head;
        int value = it->second.first;
        v.erase(it->second.second);
        v.push_front(key);
        cache[key] = make_pair(value, v.begin());
        return value;
    }

    void put(int key, int value) {
        auto it = cache.find(key);
        if (it == cache.end()) {
            // not fount it
            int len = cache.size();
            if(len == cap) {
                // last erase
                cache.erase(v.back());
                v.pop_back();
            }
            v.push_front(key);
            cache[key] = make_pair(value, v.begin());
        } else {
            // found it and swap to head;
            v.erase(it->second.second);
            v.push_front(key);
            cache[key] = make_pair(value, v.begin());
        }
        return ;
    }

private:
    typedef pair<int, list<int>::iterator> pil;

    int cap;
    list<int> v;
    unordered_map<int, pil> cache;

};
posted @ 2019-06-19 22:35  Draymonder  阅读(92)  评论(0编辑  收藏  举报