[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;
    }
};

posted @ 2017-06-14 23:30  mioopoi  阅读(159)  评论(0编辑  收藏  举报