-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path49_LRU.cpp
123 lines (109 loc) · 2.51 KB
/
49_LRU.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <list>
#include <unordered_map>
using namespace std;
/*
class Node{
public:
Node(int k, int v):key(k),value(v) {}
int key;
int value;
};
class LRUCache {
public:
LRUCache(int capacity):cpcty(capacity) {}
int get(int key) {
if(l.empty())return -1;
for(auto it = l.begin(); it != l.end(); ++it){
if((*it).key == key){
Node tmp((*it).key, (*it).value);
l.erase(it);
l.push_back(tmp);
return tmp.value;
}
}
return -1;
}
void put(int key, int value) {
Node tmp(key, value);
if(get(key) != -1){
for(auto it = l.begin(); it != l.end(); ++it){
if((*it).key == key){
l.erase(it);
break;
}
}
}
else{
if(!l.empty()&&(int)l.size() == cpcty){
//cout << value << ' ' << l.front().value <<endl;
l.pop_front();
}
}
l.push_back(tmp);
}
void out_put()
{
for(auto e:l)
{
cout << e.key << ' ' << e.value << '|';
}
cout << endl;
}
list<Node> l;
private:
int cpcty;
};
*/
static const auto _=[]{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class LRUCache {
public:
LRUCache(int capacity):cpcty(capacity) {}
int get(int key) {
auto it = umap.find(key);
if(it == umap.end()){
return -1;
}
else{
/*
pair<int, int> tmp = make_pair(key, it->second->second);
l.erase(it->second);
l.push_front(tmp);
*/
l.splice(l.begin(), l, it->second);
return it->second->second;
}
}
void put(int key, int value) {
auto it = umap.find(key);
if(it != umap.end()){
l.erase(it->second);
}
l.push_front(make_pair(key, value));
umap[key] = l.begin();
if((int)umap.size() > cpcty){
int del = l.rbegin()->first;
l.pop_back();
umap.erase(del);
}
}
private:
int cpcty;
list<pair<int, int>> l;
unordered_map<int, list<pair<int, int>>::iterator> umap;
};
int main()
{
LRUCache cache(2);
cache.put(2,1);
cache.put(2,2);
cout << cache.get(2) << endl;
cache.put(1,1);
cache.put(4,1);
cout << cache.get(2) << endl;
return 0;
}