-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru.cpp
More file actions
54 lines (51 loc) · 1.4 KB
/
lru.cpp
File metadata and controls
54 lines (51 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "bits/stdc++.h"
using namespace std;
class LRUCache {
int maxn;
list<int> ls;
unordered_map<int, list<int>::iterator> mp;
unordered_map<int, int> val;
LRUCache(int n) { maxn = n; }
int get(int key) {
if (mp.find(key) != mp.end()) {
int value = val[key];
auto it = mp[key];
ls.erase(it);
ls.push_back(key);
mp[key] = --ls.end();
return value;
} else {
return -1;
}
}
void put(int key, int value) {
if (mp.find(key) != mp.end()) {
int value = val[key];
auto it = mp[key];
ls.erase(it);
ls.push_back(key);
mp[key] = --ls.end();
val[key] = value;
} else {
if (ls.size() == maxn) {
mp.erase(*ls.begin());
ls.pop_front();
}
ls.push_back(key);
mp[key] = --ls.end();
val[key] = value;
}
}
};
int main() {
LRUCache cache = LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
}