-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
36 lines (31 loc) · 751 Bytes
/
LRUCache.cpp
File metadata and controls
36 lines (31 loc) · 751 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
35
36
class LRUCache {
public:
int cap;
list<int>key_list;
unordered_map<int,int>mp;
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
if(mp.find(key) == mp.end() )
return -1;
else{
key_list.remove(key);
key_list.push_back(key);
return mp[key];
}
}
void put(int key, int value) {
if(mp.find(key) != mp.end() ){
mp.erase(key);
key_list.remove(key);
}
if(key_list.size() == cap){
int temp = key_list.front();
key_list.pop_front();
mp.erase(temp);
}
mp[key] = value;
key_list.push_back(key);
}
};