• 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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    关于c:fakepath的解决办法
    golang channel 源码剖析
    深入虚拟内存(Virtual Memory,VM)
    浅析 golang module
    浅析 golang interface 实现原理
    Golang channel实现
    LCS(最长公共字序列)实现
    Golang令牌桶-频率限制
    OpenGL(3)-三角形
    OpenGL(2)-窗口
  • 原文地址:https://www.cnblogs.com/lightac/p/12957131.html
Copyright © 2020-2023  润新知