146. LRU Cache

来源:互联网 发布:seo资源网 编辑:程序博客网 时间:2024/04/30 19:10

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缓存的实现。在这种方法中,如果写入内存的时候容量不足了,最近没用的那一块内存将被换出,以存入新的数据。这里用unordered_map和list来实现。在链表中,最近用过的点在头部,最近没用过的点在尾部,哈希映射表用来保存键值和节点的对应关系。在get函数中,如果在映射表中找不到key对应的那一个节点,返回1;如果找到了,将该节点移到链表的头部(做法是复制和删除原来的点,将复制得到的点插在头部),表示最新用过这个点。在set函数中,如果在映射表中找不到key对应的那一个节点,则要插入该节点,因为是最近用过的,所以查到头部,注意如果链表长度到达最大值,要把最后的节点删除;如果找到了,则更新这个点的实值,然后将该点移到头部(做法和上面的一样)。这样就简单实现了这种缓存机制。


代码:

class LRUCache{public:    LRUCache(int capacity):Max(capacity){    }        int get(int key) {        auto it=um.find(key);        if(it==um.end()) return -1;        auto lit=it->second;        node newnode(lit->key,lit->val);        ls.erase(lit);        ls.push_front(newnode);        um[key]=ls.begin();        return ls.begin()->val;    }        void set(int key, int val) {auto it=um.find(key);        if(it==um.end())        {        if(ls.size()==Max)        {        um.erase(ls.back().key);        ls.pop_back();}ls.push_front(node(key,val));um[key]=ls.begin();}else{auto lit=it->second;node newnode(key,val);ls.erase(lit);ls.push_front(newnode);um[key]=ls.begin();}    }    private:struct node{int key;int val;node(int k,int v):key(k),val(v){}};list<node>ls;unordered_map<int,list<node>::iterator>um;int Max;};


0 0
原创粉丝点击