-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.cpp
More file actions
34 lines (31 loc) · 722 Bytes
/
146.cpp
File metadata and controls
34 lines (31 loc) · 722 Bytes
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
#include<bits/stdc++.h>
using namespace std;
list<int> cache;
unordered_map<int, pair<int, list<int>::iterator>> mp;
int cache_size;
LRUCache(int capacity) {
cache_size = capacity;
}
int get(int key) {
if (mp.find(key) != mp.end()) {
list<int>::iterator it = mp[key].second;
cache.erase(it);
cache.push_front(key);
mp[key].second = cache.begin();
return mp[key].first;
}
return -1;
}
void put(int key, int value) {
if (mp.find(key) != mp.end()) {
cache.erase(mp[key].second);
}
cache.push_front(key);
mp[key].second = cache.begin();
mp[key].first = value;
if (mp.size() > cache_size) {
int least_used = cache.back();
cache.pop_back();
mp.erase(least_used);
}
}