LRU cache

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 class LRUCache{
 2 public:
 3     LRUCache(int capacity) {
 4         max_capacity = capacity;
 5         cur_size = 0;
 6     }
 7     
 8     int get(int key) {
 9         int value;
10         if (hash.find(key) == hash.end()) {
11             return -1;
12         }
13         else {
14             auto it = hash[key];
15             value = it->second;
16             cache.push_front(*it);
17             cache.erase(it); // delete
18             
19             hash[key] = cache.begin();
20         }
21         return value;
22     }
23     
24     void set(int key, int value) {
25            
26         if (hash.find(key) != hash.end()) {
27             cache.erase(hash[key]);
28             hash.erase(key);        
29         }
30         else {
31             if (cur_size < max_capacity) {
32                 cur_size++;
33             }
34             else {
35                 // delete old (key,value)
36                 list<pair<int,int> >::iterator it = cache.begin();
37                 advance(it, cur_size-1);
38                 hash.erase(it->first);
39                 cache.erase(it);
40             }
41         }
42             
43         cache.push_front(pair<int,int>(key,value));
44         hash[key] = cache.begin();
45     }
46 
47 private:
48     int max_capacity;
49     int cur_size;
50     list<pair<int,int> > cache;
51     unordered_map<int, list<pair<int,int> >::iterator> hash;
52 };

 

posted @ 2014-03-28 07:26  beehard  阅读(196)  评论(0编辑  收藏  举报