146. LRU Cache

problem

solution

option 1

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class Node{
public:
int val, key ;
Node *prev, * next;
Node(int k,int v){
key = k;
val = v;
prev= nullptr;
next = nullptr;
}
};
class DoubleLinkedList{
private:
int size;
Node *head, *tail;
public:

DoubleLinkedList(){
size = 0;
head = new Node(0,0);
tail = new Node(0,0);
head->next = tail;
tail->prev = head;
}
// push back
void push_back(Node *node){
// Node *node = new Node(x);
node->next = tail;
node->prev = tail->prev;
tail->prev->next = node;
tail->prev = node;
size++;
}
void push_front(Node *node){
// Node *node = new Node(x);
node->next= head->next;
head->next->prev = node;
head->next = node;
node->prev = head;
size++;
}
// pop back
void pop_back(){
Node *node = tail->prev;
// int ret = node->val;
if(node == head) return ;
tail->prev = node->prev;
tail->prev->next = tail;
size--;
// return node->val;
}
Node* pop_front(){
Node *node = head->next;
if(node == tail) return nullptr;
head->next = node->next;
node->next->prev = head;
size--;
return node;
}
void remove(Node *node){
Node *pre = node->prev;
pre->next = node->next;
pre->next->prev = pre;
size--;
}
int getSize() {return size;}
};
class LRUCache {
private:
//key 存key, value存 Node,可以由key 找到哪個Node,再去對cache做操作
unordered_map<int,Node*> mp;
DoubleLinkedList* cache;
int cap;
public:

LRUCache(int capacity) {
cap = capacity;
cache = new DoubleLinkedList();
}

// 將key 提升為最近使用
void makeRecently(int key){
Node *node = mp[key];
cache->remove(node);
cache->push_back(node);
// mp[key] = node;
}
// 添加最近使用元素
void addRecently(int key, int val){
Node *node = new Node(key, val);
cache->push_back(node);
mp[key] = node;
}
// 刪除某一個key
void deleteKey(int key){
Node *node = mp[key];
cache->remove(node);
mp.erase(node->key);
}
// 刪除最久未使用的元素
void removeLeastRecently(){
Node *node = cache->pop_front();
mp.erase(node->key);
}

int get(int key) {
if(mp.find(key)==mp.end()) return -1;
Node* node = mp[key];
makeRecently(key);
return mp[key]->val;

}

void put(int key, int value) {
if(mp.find(key)!=mp.end()){
deleteKey(key);
addRecently(key, value);
}
else{
// 滿了
if(cache->getSize() == cap || mp.size() == cap){
removeLeastRecently();
}
addRecently(key , value);
}

}
};

/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/

analysis