-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache.cpp
71 lines (60 loc) · 1.29 KB
/
146. LRU Cache.cpp
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
68
69
70
71
class LRUCache {
public:
class node{
public:
int key;
int val;
node* next;
node* prev;
node(int _key,int _val){
key = _key;
val = _val;
next = NULL;
prev = NULL;
}
};
int n;
unordered_map<int,node*>mp;
// head and tail
node* head = new node(0,0);
node* tail = new node(0,0);
void remove(node* root){
mp.erase(root->key);
node* r1 = root->next;
node* r2 = root->prev;
r2->next = r1;
r1->prev = r2;
}
void insert(node* root){
mp[root->key] = root;
node* temp = head->next;
head->next = root;
root->next = temp;
temp->prev = root;
root->prev = head;
}
LRUCache(int capacity) {
n = capacity;
head->next = tail;
tail->prev = head;
}
int get(int key) {
if(mp.count(key)==0){
return -1;
}
node *temp = mp[key];
remove(temp);
insert(temp);
return temp->val;
}
void put(int key, int value) {
node* temp = new node(key,value);
if(mp.count(key)!=0){
remove(mp[key]);
}
if(mp.size() == n){
remove(tail->prev);
}
insert(temp);
}
};