LeetCode 146 LRU Cache 最近最少使用页面置换算法

实现一个LRU缓存器,最近最少使用页面置换算法。缓存器主要有两个成员函数,get和set,其中get函数是通过输入key来获得value,如果成功获得后,这对(key, value)升至缓存器中最常用的位置(顶部),如果key不存在,则返回-1。set函数是插入一对新的(key, value),如果原缓存器中有该key,则需要先删除掉原有的,将新的插入到缓存器的顶部。如果不存在,则直接插入到顶部。若加入新的值后缓存器超过了容量,则需要删掉一个最不常用的值,也就是底部的值。具体实现时需要三个私有变量,cap, list和map,其中cap是缓存器的容量大小,list是保存缓存器内容的列表,map是哈希表,保存关键值key和缓存器各项的迭代器之间映射,方便以O(1)的时间内找到目标项。

 1 class LRUCache {
 2 public:
 3     LRUCache(int capacity) {
 4         cap=capacity;
 5     }
 6     
 7     int get(int key) {
 8         auto it=m.find(key);
 9         if(it==m.end())
10             return -1;
11         l.splice(l.begin(),l,it->second);
12         return it->second->second;
13     }
14     
15     void put(int key, int value) {
16         auto it=m.find(key);
17         if(it!=m.end())
18             l.erase(it->second);
19         l.push_front(make_pair(key,value));
20         m[key]=l.begin();
21         if(m.size()>cap)
22         {
23             int k=l.rbegin()->first;
24             l.pop_back();
25             m.erase(k);
26         }
27     }
28 private:
29     int cap;
30     list<pair<int,int>> l;
31     unordered_map<int,list<pair<int,int>>::iterator> m;
32 };
33 
34 /**
35  * Your LRUCache object will be instantiated and called as such:
36  * LRUCache obj = new LRUCache(capacity);
37  * int param_1 = obj.get(key);
38  * obj.put(key,value);
39  */

 

posted on 2018-03-04 16:07  lina2014  阅读(331)  评论(0编辑  收藏  举报

导航