-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU_cache.cpp
More file actions
54 lines (51 loc) · 1.1 KB
/
LRU_cache.cpp
File metadata and controls
54 lines (51 loc) · 1.1 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
map<int,int> cache;
deque<int> lru;
int cap;
set<int> s;
LRUCache::LRUCache(int capacity) {
cap = capacity;
cache.clear();
lru.clear();
s.clear();
}
int LRUCache::get(int key) {
if(cache.find(key)==cache.end())
return -1;
int id;
for(int i=0;i<lru.size();i++)
if(lru[i]==key){
id = i;
break;
}
lru.erase(lru.begin()+id);
lru.push_back(key);
return cache[key];
}
void LRUCache::set(int key, int value) {
if(cache.size()<cap || cache.count(key)>0){
cache[key] = value;
if(s.find(key)==s.end()){
s.insert(key);
lru.push_back(key);
}
else{
int id;
for(int i=0;i<lru.size();i++)
if(lru[i]==key){
id = i;
break;
}
lru.erase(lru.begin()+id);
lru.push_back(key);
}
}
else{
int val = lru.front();
lru.pop_front();
cache.erase(val);
s.erase(val);
cache[key] = value;
s.insert(key);
lru.push_back(key);
}
}