首页 > 其他 > 详细

LeetCode LRU Cache

时间:2014-04-03 09:43:39      阅读:562      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 class LRUCache{
 2 private:
 3     int max_size;
 4     unordered_map<int, list<pair<int, int> >::iterator> hash;
 5     list<pair<int, int> > lru_stack;
 6 public:
 7     LRUCache(int capacity) {
 8         if (capacity < 1) capacity = 0;
 9         max_size = capacity;
10     }
11 
12     int get(int key) {
13         unordered_map<int, list<pair<int, int> >::iterator>::iterator miter = hash.find(key);
14         list<pair<int, int> >::iterator liter;
15         if (miter == hash.end()) {
16             return -1;
17         } else {
18             liter = miter->second;
19             int val = liter->second;
20             lru_stack.erase(liter);
21             miter->second = liter = lru_stack.insert(lru_stack.begin(), make_pair(key, val));
22             return liter->second;
23         }
24     }
25 
26     void set(int key, int value) {
27         if (max_size == 0) return;
28         unordered_map<int, list<pair<int, int> >::iterator>::iterator miter = hash.find(key);
29         list<pair<int, int> >::iterator liter;
30         if (miter == hash.end()) {   // key not exists in the cache
31             if (hash.size() == max_size) {
32                 // invalidate LRU item to avoid overflow
33                 hash.erase(lru_stack.back().first);
34                 lru_stack.pop_back();
35             }
36             liter = lru_stack.insert(lru_stack.begin(), make_pair(key, value));
37             hash.insert(make_pair(key, liter));
38         } else {    // key already exists, so replace the value with new one
39             liter = miter->second;
40             lru_stack.erase(liter);
41             miter->second = lru_stack.insert(lru_stack.begin(), make_pair(key, value));
42         }
43     }
44 };
bubuko.com,布布扣

用一个链表来维护LRU关系,map来做hash,用了std库,如果纯粹自己手工写可能会花多点时间

LeetCode LRU Cache,布布扣,bubuko.com

LeetCode LRU Cache

原文:http://www.cnblogs.com/lailailai/p/3641789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!