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);
     */

    对封装的一些见解

    希望用自己的努力为自己赢得荣誉。
  • 相关阅读:
    (转)灵活运用 SQL SERVER FOR XML PATH
    Docker
    Springboot
    Redis
    Centos7.6在线安装mysql8.0.16
    Centos7.6安装jdk1.8
    Dubbo
    相关性检验
    逻辑回归和决策树上的一些区别
    postgresql 学习手册(客户端)
  • 原文地址:https://www.cnblogs.com/Mmasker/p/15218001.html
Copyright © 2011-2022 走看看