LRU Cache

题目146:LRU Cache

题目描述:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

题目分析:
设计数据结构实现LRU,支持get和set操作,尽可能高效地操作。看get和set操作的定义,实际上是支持3个操作,查找、插入、删除,查找快自然是哈希表,插入和删除快自然是链表,如果是单链表每次插入删除都需要找到该链表的前驱,所以我们采用双向链表(因为双向链表保存要删除结点的前驱pre,不再需要查找获取前驱)。
链表结点保存的内容自然有:pre、next、key、val。

现在,数据结构我们确定了,那怎么对数据结构进行操作来支持get和set呢?

get操作
1. 如果哈希表中没有查找的key,则返回-1;
2. 如果哈希表中找到key,则首先将该结点移动到双向链表的尾部,改变哈希表中对于的指针,再将该结点的值val返回;
set操作
1. 如果哈希表中有查找的结点,则直接修改结点的val值,再将该结点移动到双向链表的尾部;
2. 如果哈希表中没有要查找的结点,则先判断缓存空间是否足够,如果缓存空间足够,则创建新结点并插入双向链表尾部,添加到哈希表中;如果缓存空间不足,则从双向链表头部删除结点后,并从哈希表中删除该结点,再创建新结点并插入双向链表尾部;

好了,过程清晰了,写代码时注意一些特殊的边界情况。
代码如下:

/* 链表结点结构体 */
struct Node {
    Node *pre;
    Node *next;
    int val;
    int key;
    Node(int k, int v): pre(NULL), next(NULL), key(k), val(v){};
};
class LRUCache{
private:
    map<int, Node *> mp;
    int cap;
    Node *tail; /* 头指针指向双向链表头 */
    Node *head; /* 尾指针指向双向链表尾 */
public:
    LRUCache(int capacity) {
        cap = capacity;
        /* clear()将map容器中的都删除 */
        mp.clear();
        head = 0;
        tail = 0;
    }
    /* 都是在双向链表尾部插入 */
    void InsertTail(Node *node) {
        if (head == 0) {
            head = node;
            tail = node;
        } else {
            tail->next = node;
            node->pre = tail;
            tail = node;
        }
    }
    /* 移动结点都是移动到双向链表尾部 */
    void MoveTail(Node *node) {
        if (node == tail)
            return;
        else {
            if (node == head) {
                node->next->pre = 0;
                head = node->next;
                tail->next = node;
                node->pre = tail;
                tail = node;
            } else {
                node->next->pre = node->pre;
                node->pre->next = node->next;
                tail->next = node;
                node->pre = tail;
                tail = node;
            }
            /* 新的尾结点next是空 */
            node->next = 0;
        }
    }
    /* 从双向链表的头部删除结点 */
    void RemoveHead(Node *node) {
        Node *del = head;
        head = head->next;
        /* 释放结点占的空间 */
        delete del;
        if (head)
            head->pre = 0;
        else 
            tail = 0;
    }

    int get(int key) {
        if (mp.find(key) == mp.end())
            return -1;
        else {
            Node *temp = mp[key];
            MoveTail(temp);
            return temp->val;
        }
    }

    void set(int key, int value) {
        if (mp.find(key) == mp.end()) {
            if (mp.size() == cap) {
                /* 从map容器中删除一个结点对 */
                mp.erase(head->key);
                RemoveHead(head);
            }
            Node *node = new Node(key, value);
            mp[key] = node;
            InsertTail(node);
        } else {
            MoveTail(mp[key]);
            mp[key]->val = value;
        }
    }
};

其中:
1. 类中private成员可被类的成员函数和友元函数访问;
2. map是STL关联容器的一种,内部实现是红黑树,支持mp[key],下标访问。
3. map中插入< key, val>对的方法有3种:
(1)map.insert(pair< int, int>(1, 22));
(2)map.insert(map< int, int>::value_type(1, 22));
(3)map[1] = 22;
当map已经有该key时,采用(1)和(2)的方式,则不能插入数据,但采用(3)的方式可以覆盖原来的值。
3. map.clear(),删除map容器中的所有元素;
4. map.erase(),从map中删除元素,可以删除一个元素,如map.erase(key),或map.erase(iter),iter是迭代器;也可以删除多个元素,map.erase(iter1, iter2),一段范围;

参考:
http://yucoding.blogspot.com/2013/12/leetcode-question-lru-cache.html
http://www.cnblogs.com/TenosDoIt/p/3417157.html

猜你喜欢

转载自blog.csdn.net/zxc995293774/article/details/49008545