-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#52.cpp
More file actions
67 lines (59 loc) · 1.18 KB
/
#52.cpp
File metadata and controls
67 lines (59 loc) · 1.18 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
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <deque>
#include <unordered_map>
#include <string>
#include <sstream>
using namespace std;
class LRUCache {
int maxSize;
deque<string> Q;
unordered_map<string, pair<int, deque<string>::iterator>> m;
void update(string key) {
Q.erase(m[key].second);
Q.push_front(key);
m[key] = make_pair(m[key].first, Q.begin());
}
public:
LRUCache(int n) {
maxSize = n;
}
int get(string key) {
if (m.find(key) == m.end())
return -1;
update(key);
return m[key].first;
}
void set(string key, int value) {
if (m.find(key) != m.end()) {
update(key);
} else if (Q.size() == maxSize) {
m.erase(Q.back());
Q.pop_back();
Q.push_front(key);
} else {
Q.push_front(key);
}
m[key] = make_pair(value, Q.begin());
}
};
int main() {
LRUCache cache = LRUCache(3);
string inp;
while (cin >> inp) {
string token;
istringstream ss(inp);
while (getline(ss, token, ',')) {
if (token == "get") {
string key;
getline(ss, key, ',');
cout << cache.get(key) << endl;
} else if (token == "set") {
string key;
getline(ss, key, ',');
getline(ss, token, ',');
int val = stoi(token);
cache.set(key, val);
}
}
}
}