@@ -219,6 +219,65 @@ if (cap == cache.size()) {
219
219
220
220
![ labuladong] ( ../pictures/labuladong.png )
221
221
222
+ [ yuxiang-zhang] ( https://github.com/yuxiang-zhang ) 提供 C++ 代码:
223
+
224
+ ``` cpp
225
+ class LRUCache {
226
+ // key -> iterator to pair(key, val) in the list
227
+ unordered_map<int, list<pair<int, int>>::iterator> map;
228
+
229
+ // pair(k1, v1) <-> pair(k2, v2)...
230
+ list<pair<int, int>> cache;
231
+
232
+ // 最大容量
233
+ int cap;
234
+ public:
235
+ LRUCache(int capacity) : cap(capacity) {}
236
+
237
+ int get(int key) {
238
+ if(map.find(key) == map.end()) {
239
+ return -1;
240
+ }
241
+
242
+ int val = map[ key] ->second;
243
+
244
+ // 利用 put 方法把该数据提前
245
+ put(key, val);
246
+
247
+ return val;
248
+ }
249
+
250
+ void put(int key, int value) {
251
+ pair<int, int> x = {key, value};
252
+
253
+ if(map.find(key) != map.end()) {
254
+
255
+ // 删除旧的节点
256
+ cache.erase(map[ key] );
257
+ // 新的插到头部
258
+ cache.emplace_front(x);
259
+
260
+ // 更新 map 中对应的数据
261
+ map[ key] = cache.begin();
262
CBBB
+
263
+ } else {
264
+
265
+ if(cap == cache.size()) {
266
+ // 删除链表最后一个数据
267
+ pair<int, int> last = cache.back(); cache.pop_back();
268
+
269
+ map.erase(last.first);
270
+ }
271
+
272
+ // 直接添加到头部
273
+ cache.emplace_front(x);
274
+ map[ key] = cache.begin();
275
+
276
+ }
277
+ }
278
+ };
279
+ ```
280
+
222
281
[eric wang](https://www.github.com/eric496) 提供 Python3 代码
223
282
224
283
```python
@@ -290,4 +349,4 @@ class LRUCache:
290
349
291
350
[下一篇:二叉搜索树操作集锦](../数据结构系列/二叉搜索树操作集锦.md)
292
351
293
- [ 目录] ( ../README.md#目录 )
352
+ [目录](../README.md#目录)
0 commit comments