-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_unordered_map_n.cpp
69 lines (59 loc) · 1.49 KB
/
AC_unordered_map_n.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_unordered_map_n.cpp
* Create Date: 2015-03-24 09:36:06
* Descripton: Use unordered_map(hash).
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class LRUCache{
private:
typedef list<int> L;
// map <key, pair <value, list.iterator> >
typedef unordered_map<int, pair<int, L::iterator> > UM;
int _capacity;
L used;
UM cache;
void touch(UM::iterator it) {
// move the node to front of list
int key = it->first;
used.erase(it->second.second);
used.push_front(key);
it->second.second = used.begin();
}
public:
LRUCache(int capacity) {
_capacity = capacity;
}
int get(int key) {
auto it = cache.find(key);
if (it == cache.end())
return -1;
touch(it);
return it->second.first;
}
void set(int key, int value) {
auto it = cache.find(key);
if (it == cache.end()) {
// if key not in cache, then add key
while (cache.size() >= _capacity) {
cache.erase(used.back());
used.pop_back();
}
used.push_front(key);
} else {
touch(it);
}
cache[key] = make_pair(value, used.begin());
}
};
int main() {
LRUCache l(1);
l.set(2,1);
cout << l.get(2) << endl;
l.set(3,2);
cout << l.get(2) << endl;
cout << l.get(3) << endl;
return 0;
}