LRU

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
class LRUCache {
public:
list<int> link;
map<int, int> m;
int capacity;
LRUCache(int capacity) {
this->capacity = capacity;
}

int get(int key) {
if(m.find(key) == m.end()) {
return -1;
} else {
link.remove(key);
link.push_front(key);
}
return m[key];
}

void put(int key, int value) {
if (m.find(key) != m.end()) { //已存在
m[key] = value;
link.remove(key);
link.push_front(key);
} else { //不存在
if (m.size() >= capacity) {
int keyLast = link.back();
link.pop_back();
m.erase(keyLast);

link.push_front(key);
m[key] = value;
} else {
m[key] = value;
link.push_front(key);
}
}
}
};