LRU Cache

来源:互联网 发布:创建wifi热点软件 编辑:程序博客网 时间:2024/06/02 00:58

参考:http://fisherlei.blogspot.tw/2013/11/leetcode-lru-cache-solution.html

实现一个LRU的缓存。当要插入一个新的数值时,缓存的存储的个数超过预定的大小时,将之前访问最少的元素移出缓存。


实现方法:用一个双向链表来存储真实的value值,用一个hash map来保存key和它对应的value在双向链表的地址。

每次访问key对应的value时,就把这个value移到链表的头部。当要插入一个新值时,如果空间大小超出了预定的大小时,

则删除链表尾部的值,再将新值插入链表的头部。


#include <map>#include <cstdio>#include <iostream>#include <unordered_map>#include <list>using namespace std;struct CacheItem {public:int key;int value;CacheItem(int k, int v): key(k), value(v) {}};class LRUCache{public:    LRUCache(int capacity) {m_capacity = capacity;    }        int get(int key) {       if(m_map.find(key) == m_map.end()) return -1;   moveToHead(key);   return m_map[key]->value;    }        void set(int key, int value) {if(m_map.find(key) == m_map.end()) {CacheItem item(key, value);if(LRU_cache.size() >= m_capacity) {m_map.erase(LRU_cache.back().key);LRU_cache.pop_back();}LRU_cache.push_front(item);m_map[key] = LRU_cache.begin();return;}m_map[key]->value = value;moveToHead(key);    }private:    unordered_map<int, list<CacheItem>::iterator> m_map;list<CacheItem> LRU_cache;int m_capacity;    void moveToHead(int key) {CacheItem item = *m_map[key];LRU_cache.erase(m_map[key]);LRU_cache.push_front(item);m_map[key] = LRU_cache.begin();}};


0 0
原创粉丝点击