zoukankan      html  css  js  c++  java
  • 设计数据结构之LRU缓存

    leetcode 146. LRU Cache

    class LRUCache {
    private:
        struct Node {
            
            int key;
            int val;
            
            Node* prev;
            Node* next;
            
            Node(int k, int v):key(k), val(v), prev(NULL), next(NULL){}
            Node() = default;
        };
        
        void removeLastNode(){
            auto last = tail->prev;
            last->prev->next = tail;
            tail->prev = last->prev;
            cache.erase(last->key);
            delete last;
        }
        
        void insertHead(Node* node){
           
            node->next = head->next;
            head->next->prev = node;
            head->next = node;
            node->prev = head;
        }
        
        void detachNode(Node* node){
            node->prev->next = node->next;
            node->next->prev = node->prev;
        }
        
        Node* head;
        Node* tail;
        int cap;
        unordered_map<int, Node*> cache;
    public:
        LRUCache(int capacity) {
            head = new Node;
            tail = new Node;
            head->next = tail;
            tail->prev = head;
            cap = capacity;
        }
        
        int get(int key) {
            if(cache.find(key) == cache.end()) return -1;
            detachNode(cache[key]);
            insertHead(cache[key]);
            return cache[key]->val;
        }
        
        void put(int key, int value) {
            if(cache.find(key) != cache.end()){ 
                cache[key]->val = value; 
                detachNode(cache[key]);                              
            } else {
                Node* newNode = new Node(key, value);
                if(cache.size() == cap) removeLastNode();
                cache[key] = newNode;
            }
            insertHead(cache[key]);
        }
    };
    
    /**
     * 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);
     */
    
  • 相关阅读:
    PHP生成pdf文档
    PHP将数据库数据批量生成word文档
    三个常用的PHP图表类库
    Javascript——(1)
    python学习HTML之CSS(2)
    python学习HTML之CSS
    python学习之HTML
    python学习之rabbitmq
    第10周15/16/17
    多进程
  • 原文地址:https://www.cnblogs.com/qbits/p/11362615.html
Copyright © 2011-2022 走看看