leetcode:LRU Cache

来源:互联网 发布:python爬虫工程师 编辑:程序博客网 时间:2024/05/17 05:06

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 or set)都使用哈希值找到这个元素在双链表中的位置,然后将它移到最前面,如果缓存已满就删除队尾的元素。哈希中放的是元素的地址,在新增、移动和删除元素的时候都要在Hash表中作对应修改,而双向链表主要是为了方便删除。

class Node{public:    int key, val;    Node *pre, *next;    Node(int k, int v): key(k), val(v), pre(NULL), next(NULL) {}};class LRUCache{    map<int, Node*> mp;    map<int, Node*>::iterator iter;    int used, cap;    Node *head, *tail;public:    LRUCache(int capacity) {        mp.clear();        used = 0, cap = capacity;        head = new Node(0, 0);        tail = new Node(0, 0);        head->next = tail, tail->pre = head;    }    ~LRUCache(){        for (Node *n = head, *nnext; n; n = nnext) {            nnext = n->next;            delete n;        }    }    int get(int key) {        if ((iter = mp.find(key)) != mp.end()) {            movetoFirst(iter->second);            return iter->second->val;        }else            return -1;    }    void set(int key, int value) {        if ((iter = mp.find(key)) != mp.end()) {            iter->second->val = value;            movetoFirst(iter->second);        } else {            Node *node;            if (used == cap) {                mp.erase(tail->pre->key);                node = tail->pre;                node->key = key, node->val = value;            } else {                node = new Node(key, value);                used++;            }            mp[node->key] = node;            movetoFirst(node);        }    }    void movetoFirst(Node *node) {        if (node->pre && node->next) {            node->pre->next = node->next;            node->next->pre = node->pre;        }        node->pre = head, node->next = head->next;        head->next->pre = node, head->next = node;    }};


1 0