LeetCode LRU Cache

来源:互联网 发布:linux排序命令 编辑:程序博客网 时间:2024/06/01 10:30

题目:

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.

分析参考:http://www.csdn123.com/html/itweb/20131110/214844.htm

struct CacheNode {int key;int value;CacheNode(int k, int v) : key(k), value(v) {}};class LRUCache{public:LRUCache(int capacity) {size = capacity;}int get(int key) {if (cacheMap.find(key) == cacheMap.end())return -1;//将要查找的CacheNode放在链首cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);//更新map中该节点的地址cacheMap[key] = cacheList.begin();return cacheMap[key]->value;}void set(int key, int value) {//插入节点if (cacheMap.find(key) == cacheMap.end()) {//删除尾部节点if (cacheList.size() == size) {cacheMap.erase(cacheList.back().key);cacheList.pop_back();}cacheList.push_front(CacheNode(key, value));cacheMap[key] = cacheList.begin();}else {cacheMap[key]->value = value;cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);cacheMap[key] = cacheList.begin();}}private:int size;list<CacheNode> cacheList;unordered_map<int, list<CacheNode>::iterator> cacheMap;};


0 0
原创粉丝点击