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

LeetCode – Refresh – LRU

时间:2015-03-20 09:12:45      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

 1 struct Node {
 2     int key, value;
 3     Node(int k, int v) : key(k), value(v) {}
 4 };
 5 
 6 class LRUCache{
 7 private:
 8     int size;
 9     list<Node> nlist;
10     unordered_map<int, list<Node>::iterator> nmap;
11 public:
12     LRUCache(int capacity) {
13         size = capacity;
14     }
15     
16     int get(int key) {
17         if (nmap.find(key) != nmap.end()) {
18             nlist.splice(nlist.begin(), nlist, nmap[key]);
19             nmap[key] = nlist.begin();
20             return nlist.begin()->value;
21         }
22         return -1;
23     }
24     
25     void set(int key, int value) {
26         if (nmap.find(key) == nmap.end()) {
27             if (size == nlist.size()) {
28                 nmap.erase(nlist.back().key);
29                 nlist.pop_back();
30             }
31             nlist.push_front(Node(key, value));
32             nmap[key] = nlist.begin();
33         } else {
34             nlist.splice(nlist.begin(), nlist, nmap[key]);
35             nmap[key] = nlist.begin();
36             nlist.begin()->value = value;
37         }
38     }
39 };

 

LeetCode – Refresh – LRU

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352710.html

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