10000 LRU算法 C++版本 (#326) · coder-chenhao/fucking-algorithm@7e2163c · GitHub
[go: up one dir, main page]

Skip to content

Commit 7e2163c

Browse files
author
yuxiang-zhang
authored
LRU算法 C++版本 (labuladong#326)
1 parent fe03677 commit 7e2163c

File tree

1 file changed

+60
-1
lines changed

1 file changed

+60
-1
lines changed

高频面试系列/LRU算法.md

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,65 @@ if (cap == cache.size()) {
219219

220220
![labuladong](../pictures/labuladong.png)
221221

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+
222281
[eric wang](https://www.github.com/eric496) 提供 Python3 代码
223282
224283
```python
@@ -290,4 +349,4 @@ class LRUCache:
290349

291350
[下一篇:二叉搜索树操作集锦](../数据结构系列/二叉搜索树操作集锦.md)
292351

293-
[目录](../README.md#目录)
352+
[目录](../README.md#目录)

0 commit comments

Comments
 (0)
0