-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.LRU Cache
More file actions
49 lines (43 loc) · 1.26 KB
/
Copy path146.LRU Cache
File metadata and controls
49 lines (43 loc) · 1.26 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
//solution:
//easy
class LRUCache{
public:
LRUCache(int capacity):capacity(capacity) {
}
int get(int key) {
if(hash.find(key)==hash.end())
return -1;
else{
nodeList.splice(nodeList.begin(),nodeList,hash[key]);
hash[key]=nodeList.begin();
return nodeList.begin()->value;
}
}
void set(int key, int value) {
if(hash.find(key)!=hash.end()){
nodeList.splice(nodeList.begin(),nodeList,hash[key]);
hash[key]=nodeList.begin();
nodeList.begin()->value=value;
}
else{
if(hash.size()<capacity){
nodeList.push_front(node(key,value));
hash[key]=nodeList.begin();
}
else{
hash.erase(nodeList.back().key);
nodeList.pop_back();
nodeList.push_front(node(key,value));
hash[key]=nodeList.begin();
}
}
}
int capacity;
struct node{
int key;
int value;
node(int key,int value):key(key),value(value){};
};
list<node> nodeList;
unordered_map<int,list<node>::iterator> hash;
};