zoukankan      html  css  js  c++  java
  • [LeetCode] LRU Cache

    https://leetcode.com/problems/lru-cache/#/description

    很重要的练习题。双端链表+哈希表。

    关键的操作是从链表中取出一个节点再放入链表尾部。

    class LRUCache {
    public:
        // @param capacity, an integer
        LRUCache(int capacity) {
            this->capacity = capacity;
            hashmap.clear();
            head = new Node(-1, -1);
            tail = new Node(-1, -1);
            head->next = tail;
            tail->prev = head;
        }
        
        // @return an integer
        int get(int key) {
            if (hashmap.count(key) == 0) {
                return -1;
            }
            // remove current
            Node* node = hashmap[key];
            node->prev->next = node->next;
            node->next->prev = node->prev;
            // move to tail
            move_to_tail(hashmap[key]);
            
            return node->value;
        }
    
        // @param key, an integer
        // @param value, an integer
        // @return nothing
        void put(int key, int value) {
            if (get(key) != -1) {
                hashmap[key]->value = value;
                return;
            }
            if (hashmap.size() == capacity) {
                // delete the front node
                hashmap.erase(head->next->key);
                Node* front = head->next;
                head->next = head->next->next;
                head->next->prev = head;
                delete front;
            }
            // insert the new node
            Node* new_node = new Node(key, value);
            hashmap[key] = new_node;
            move_to_tail(new_node);
        }
    
    private:
        class Node {
        public:
            int key;
            int value;
            Node* prev;
            Node* next;
            Node (int _key, int _value) {
                key = _key;
                value = _value;
                prev = NULL;
                next = NULL;
            }
        };
        
        int capacity;
        unordered_map<int, Node*> hashmap;
        Node* head;
        Node* tail;
        
        void move_to_tail(Node* node) {
            node->next = tail;
            node->prev = tail->prev;
            node->prev->next = node;
            tail->prev = node;
        }
    };
    
    
  • 相关阅读:
    自我介绍
    秋季学期总结
    第七周编程总结
    第六周作业
    第五周编程总结
    第四周编程总结
    第三周作业
    第二周作业
    抓老鼠啊~亏了还是赚了
    币值转换
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/7011566.html
Copyright © 2011-2022 走看看