zoukankan      html  css  js  c++  java
  • 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;
    
    };
    
  • 相关阅读:
    数组_leetcode283
    数组_leetcode438
    数组_leetcode215
    数组_leetcode167
    数组_leetcode209
    数组_leetcode88
    数组_leetcode80
    数组_leetcode76
    数组_leetcode75
    数组_leetcode27
  • 原文地址:https://www.cnblogs.com/Draymonder/p/11055447.html
Copyright © 2011-2022 走看看