码迷,mamicode.com
首页 > 其他好文 > 详细

LRU Cache

时间:2014-09-13 20:05:25      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   for   div   sp   

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.

 1 struct cacheNode
 2     {
 3         int key;
 4         int data;
 5     };
 6 
 7 class LRUCache{
 8 public:
 9     
10     
11     LRUCache(int capacity) 
12     {
13         size = capacity;
14     }
15     
16     int get(int key) 
17     {
18         if( cacheMap.find(key) != cacheMap.end() )
19         {
20             list<cacheNode>:: iterator it = cacheMap[key];
21             cacheList.splice(cacheList.begin(), cacheList, it);
22             cacheMap[key] = cacheList.begin();
23             return cacheList.begin()->data;
24         }
25         else
26             return -1;
27     }
28     
29     void set(int key, int value) 
30     {
31         if( cacheMap.find(key) != cacheMap.end() )
32         {
33             list<cacheNode>::iterator it = cacheMap[key];
34             cacheList.splice(cacheList.begin(), cacheList, it);
35             cacheMap[key] = cacheList.begin();
36             cacheList.begin()->data = value;
37         }
38         
39         else
40         {
41             if(cacheList.size() == size)
42             {
43                 cacheMap.erase(cacheList.back().key);
44                 cacheList.pop_back();
45             }
46             
47             cacheNode node;
48             node.key = key;
49             node.data = value;
50             cacheList.push_front(node);
51             cacheMap[key] = cacheList.begin();
52         }
53     }
54     
55 private:
56     int size;
57     list<cacheNode> cacheList;
58     unordered_map<int, list<cacheNode>::iterator> cacheMap;
59 };

 

LRU Cache

标签:des   style   blog   color   io   os   for   div   sp   

原文地址:http://www.cnblogs.com/YQCblog/p/3970209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!