zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    };
    
    作者:LightAc
    出处:https://www.cnblogs.com/lightac/
    联系:
    Email: dzz@stu.ouc.edu.cn
    QQ: 1171613053
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    开博说两句
    学习总结 (持续更新)
    ip代理 120203
    [vs2005]关于预编绎网站的问题[已预编译此应用程序的错误]
    JAVA类基础
    集合类和泛型
    IO流——字符流
    多线程和包
    多态和内部类
    抽象类与接口
  • 原文地址:https://www.cnblogs.com/lightac/p/12957131.html
Copyright © 2011-2022 走看看