zoukankan      html  css  js  c++  java
  • LRU(找工作之路,漫漫其修远兮)

    struct DList {
        int key, value;
        DList *next, *pre;
    
        DList() : key(0), value(0), next(nullptr), pre(nullptr) {}
    
        DList(int _key, int _value) : key(_key), value(_value), next(nullptr), pre(nullptr) {}
    };
    
    class LRUCache {
    private:
        int cap, nowSize = 0;
        map<int, DList *> mp;
        DList *head;
        DList *tail;
    
        void move_to_head(DList *node) {
            remove(node);
            add_to_head(node);
        }
    
        void remove(DList *node) {
            DList *Pre = node->pre;
            DList *Next = node->next;
            Pre->next = Next;
            Next->pre = Pre;
        }
    
        void add_to_head(DList *node) {
            DList *Sec = head->next;
            Sec->pre = node;
            node->next = Sec;
            head->next = node;
            node->pre = head;
        }
    
    public:
        LRUCache(int capacity) {
            mp.clear();
            cap = capacity;
            head = new DList();
            tail = new DList();
            head->next = tail;
            tail->pre = head;
        }
    
        int get(int key) {
            if (!mp.count(key)) {
                return -1;
            } else {
                DList *node = mp[key];
                move_to_head(node);
                return node->value;
            }
        }
    
        void put(int key, int value) {
            if (!mp.count(key)) {
                DList *node = new DList(key, value);
                add_to_head(node);
                nowSize++;
                mp[key] = node;
                if (nowSize > cap) {
                    mp.erase(tail->pre->key);
                    remove(tail->pre);
                    nowSize--;
                }
            } else {
                DList *node = mp[key];
                node->value = value;
                move_to_head(node);
            }
        }
    };
    
    /**
     * Your LRUCache object will be instantiated and called as such:
     * LRUCache* obj = new LRUCache(capacity);
     * int param_1 = obj->get(key);
     * obj->put(key,value);
     */

    对封装的一些见解

    希望用自己的努力为自己赢得荣誉。
  • 相关阅读:
    【狼】狼的unity3d脚本学习
    [转]关于Unity中文件读取
    【狼】unity3d 安卓播放视频替代视频纹理
    SpringMVC异常处理
    springboot 热启动
    旅游网dao层
    MyBatisPlus快速入门
    旅游网dao层
    MySQL8 修改密码验证插件
    Zookeeper环境搭建
  • 原文地址:https://www.cnblogs.com/Mmasker/p/15218001.html
Copyright © 2011-2022 走看看