LeetCode 146. LRU Cache

来源:互联网 发布:配餐软件 编辑:程序博客网 时间:2024/05/16 17:07

LRU是针对现代操作系统中Cache和内存,或是内存和磁盘的块替换而提出的。

算法原理可参见百度百科

算法实现上,

1. 用list维护LRU策略

2. 用map记录key对应的list中的结点的地址: map<key, list<Cache_node>::iterator. 若不这样做,则每次重set结点时,就需要遍历list, 将该结点放到list头部。从而可以导致O(n^2)的复杂度。


代码:

class LRUCache{public:    LRUCache(int c): capacity(c) {}        int get(int key)     {    if (content.count(key) != 0)    {LRU_update(key, content[key]->val); // is it necessary?return content[key]->val;    } else    {    return -1;    }    }        void set(int key, int value)     {        if (content.count(key) != 0) // in map        {        LRU_update(key, value);        } else if ( content.size() < capacity )        {        LRU_insert(key, value);        } else        {        LRU_replace(key, value);        }    }private:class Cache_node{public:int key;int val;Cache_node(int k, int v): key(k), val(v) {}};    void LRU_update(int key, int value)    {node_list.splice(node_list.begin(), node_list, content[key]);node_list.front().val = value; // use for setcontent[key] = node_list.begin();    }    void LRU_insert(int key, int value)    {node_list.push_front(Cache_node(key, value));    content[key] = node_list.begin();    }    void LRU_replace(int key, int value)    {content.erase( node_list.back().key );    node_list.pop_back();    LRU_insert(key, value);    }int capacity;list<Cache_node> node_list;map<int, list<Cache_node>::iterator> content;};




0 0
原创粉丝点击