@@ -63,3 +63,53 @@ public:
63
63
64
64
}
65
65
};
66
+
67
+ // 用了一个双向链表list ,一个 unorder_map辅助空间,实现了LRUCatch 原理,唯一复杂的的是当进行改变的时候要两者同时改变
68
+
69
+ class LRUCache{
70
+ private:
71
+ struct CatchNode{
72
+ int key;
73
+ int value;
74
+ CatchNode (int x,int y):key(x),value(y){};// 初始化列表
75
+ };
76
+ list<CatchNode> catchList; // 双向链表存放catch
77
+ unordered_map <int, list<CatchNode>::iterator> mapCatch; // 辅助空间查找节点对应的地址,从而不需要进行遍历
78
+ int capacity;
79
+ public:
80
+ LRUCache(int capacity) {
81
+ this->capacity = capacity;
82
+
83
+ }
84
+
85
+ int get(int key) { // 当有相同的key 取哪个呢?从经常使用的开始查找,错了,不会有相同的key存在的是进行更新然后作为最近使用的节点
86
+ if(mapCatch.find(key) == mapCatch.end())
87
+ return -1;
88
+ catchList.splice(catchList.begin(),catchList,mapCatch[key]); // splice 的使用,可以进行自我迁移的!
89
+ mapCatch[key] = catchList.begin();
90
+ return catchList.begin()->value;
91
+
92
+ }
93
+
94
+ void set(int key, int value) {
95
+ if(mapCatch.find(key) == mapCatch.end())
96
+ {
97
+ if(catchList.size() == capacity)
98
+ {
99
+ mapCatch.erase(catchList.back().key); // 把对应的map中的地址也要消除
100
+ catchList.pop_back();
101
+ }
102
+ CatchNode *newNode = new CatchNode(key,value);
103
+ catchList.push_front(*newNode);
104
+ mapCatch[key] = catchList.begin();
105
+
106
+ }
107
+ else
108
+ {
109
+ mapCatch[key]->value = value;
110
+ catchList.splice(catchList.begin(),catchList,mapCatch[key]);
111
+ mapCatch[key] = catchList.begin();
112
+ }
113
+ }
114
+ };
115
+
0 commit comments