-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache146.cpp
More file actions
80 lines (73 loc) · 1.69 KB
/
Copy pathLRUCache146.cpp
File metadata and controls
80 lines (73 loc) · 1.69 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
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
class node {
public:
int val;
int key;
node*prev, *next;
node (int v, int k): val(v), key(k){};
};
class LRUCache {
public:
unordered_map<int, node*>num;//key, index
int size = 0, limit;
node* head, *tail;
void popTail() {
node* tmp = tail->next->next;
tmp->prev = tail;
tail->next = tmp;
}
void remove(node* n) {
node* f = n->next;
node* b = n->prev;
f->prev = b;
b->next = f;
}
void add(node* n) {
node* p = head->prev;
p->next = n;
head->prev = n;
n->next = head;
n->prev = p;
}
void move2Head (node* n) {
remove(n);
add(n);
}
LRUCache(int capacity) {
limit = capacity;
head = new node(-1, -1);
tail = new node(-2, -1);
head->next = nullptr;
head->prev = tail;
tail->next = head;
tail->prev = nullptr;
}
int get(int key) {
if (num.count(key)) {
node* n = num[key];
move2Head(n);
return n->val;
}
return -1;
}
void put(int key, int value) {
if (num.count(key)) {
num[key]->val = value;
move2Head(num[key]);
} else {
if (size < limit) {
size++;
node* n = new node(value, key);
num[key] = n;
add(n);
return;
}
int temp = tail->next->key;
popTail();
node* n = new node(value, key);
num.erase(temp);
num[key] = n;
add(n);
}
return;
}
};