-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path146_LRUCache.cpp
70 lines (61 loc) · 1.73 KB
/
146_LRUCache.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
69
70
#include <cstdio>
#include <string>
#include <vector>
#include <list>
#include <unordered_map>
#include <iostream>
using namespace std;
class LRUCache {
public:
LRUCache(int capacity_)
: capacity(capacity_)
, size(0)
{
}
int get(int key) {
auto it = map.find(key);
if (it == map.end())
return -1;
recentList.splice(recentList.begin(), recentList, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = map.find(key);
if (it != map.end())
{
recentList.splice(recentList.begin(), recentList, it->second);
it->second->second = value;
}
else
{
if (size == capacity)
{
map.erase(recentList.back().first);
recentList.pop_back();
}
else
{
++size;
}
map[key] = recentList.insert(recentList.begin(), make_pair(key, value));
}
}
private:
list<pair<int, int>> recentList;
std::unordered_map<int, list<pair<int, int>>::iterator> map;
int size;
int capacity;
};
int main()
{
LRUCache cache(2 /* capacity */);
cache.put(1, 1);
cache.put(2, 2);
cout << cache.get(1) << "\n"; // returns 1
cache.put(3, 3); // evicts key 2
cout << cache.get(2) << "\n"; // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cout << cache.get(1) << "\n"; // returns -1 (not found)
cout << cache.get(3) << "\n"; // returns 3
cout << cache.get(4) << "\n"; // returns 4
}