标签:c++ leetcode 缓存 lru unordered_map
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.
方法:使用list存储key,value,使用unordered_map存储key和数据的地址(用unordered_map因为它查找性能好,底层是哈希实现的,一般O(1),而且C++11将其设置为标准),而map底层是红黑树实现的,查找性能一般是稳定在O(log(n)).
#include <iostream> #include <unordered_map> #include <list> #include <utility> using namespace std; //using namespace stdext; using namespace std::tr1; class LRUCache{ public: LRUCache(int capacity) { this->capacity=capacity; } int get(int key) { if(cacheMap.find(key)==cacheMap.end())//没有找到数据 return -1; else { cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]);//将本条数据移动到链表头部(最近访问的数据),目的是提高命中率(链表头部到链表尾部,频率依次降低) cacheMap[key]=cacheList.begin();//更新哈希表 return cacheMap[key]->second;//返回值 } } void set(int key, int value) { if(cacheMap.find(key)!=cacheMap.end())//缓存中已经有此key { cacheMap[key]->second=value;//更新值 cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]);//因为再次被set,说明访问频率高,将此记录移动到链表头部,O(1) cacheMap[key]=cacheList.begin();//更新哈希表中地址 } else//缓存中没有此key { if(cacheList.size()<capacity)//缓存未满 cacheList.push_front(make_pair(key,value));//将新数据插入到链表头部 else//缓存已经满了 { cacheMap.erase(cacheList.back().first);//删除哈希表中对应链表尾部节点的数据 cacheList.pop_back();//删除链表尾部节点(被访问频率较低的数据) cacheList.push_front(make_pair(key,value));//将新数据插入到链表头部 } cacheMap[key]=cacheList.begin();//将地址写到哈希表中 } } private: list< pair<int,int> > cacheList;//每个元素记录key,value unordered_map< int,list< pair<int,int> >::iterator > cacheMap;//记录元素的key对应的cacheList内的地址,主要是为了加快查找速度(一般O(1),如果rehash可能会不止) int capacity;//cache能装下的记录数量 }; int main() { LRUCache cache(10); cache.set(2,33); cache.set(1,11); cout<<cache.get(1)<<endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:c++ leetcode 缓存 lru unordered_map
原文地址:http://blog.csdn.net/u013861066/article/details/47361513