-
Notifications
You must be signed in to change notification settings - Fork 28
/
LRU_Cache.cpp
124 lines (116 loc) · 3.16 KB
/
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
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
class LRUCache {
public:
LRUCache(int capacity) {
LRUCache::capacity = capacity;
len = 0;
head = tail = nullptr;
}
int get(int key) {
if (table.find(key) != table.end()) {
ListNode *node = table[key];
removeNode(node);
setHead(node);
return node->value;
} else {
return -1;
}
}
void set(int key, int value) {
if(table.find(key) != table.end()) {
ListNode *curr = table[key];
curr->value = value;
removeNode(curr);
setHead(curr);
} else {
ListNode *curr = new ListNode(key, value);
if(len < capacity) {
setHead(curr);
table[key] = curr;
len++;
} else {
ListNode *tmp = tail;
tail = tail->prev;
if(tail) {
tail->next = nullptr;
}
table.erase(tmp->key);
delete tmp;
setHead(curr);
table[key] = curr;
}
}
}
private:
struct ListNode {
int key, value;
ListNode *prev, *next;
ListNode(int key, int value)
: key(key)
, value(value)
, prev(nullptr)
, next(nullptr) {
}
};
unordered_map<int, ListNode*> table;
ListNode *head, *tail;
int capacity;
int len;
void removeNode(ListNode *node) {
if(node->prev) {
node->prev->next = node->next;
} else {
head = node->next;
}
if(node->next) {
node->next->prev = node->prev;
} else {
tail = node->prev;
}
}
void setHead(ListNode *node) {
node->next = head;
node->prev = nullptr;
if(head) {
head->prev = node;
}
head = node;
if(!tail) {
tail = node;
}
}
};
// using C++ std::list
class LRUCache {
public:
LRUCache(int capacity) {
entries = list<pair<int, int>> ();
table = unordered_map<int, list<pair<int, int>>::iterator> ();
LRUCache::capacity = capacity;
}
int get(int key) {
if (table.find(key) != table.end()) {
auto entry = table[key];
entries.splice(entries.begin(), entries, entry);
return entry->second;
}
return -1;
}
void put(int key, int value) {
if (table.find(key) != table.end()) {
entries.erase(table[key]);
} else {
if(entries.size() >= capacity) {
pair<int, int> tailEntry = entries.back();
table.erase(tailEntry.first);
entries.pop_back();
}
}
pair<int, int> newEntry = {key, value};
entries.push_front(newEntry);
table[key] = entries.begin();
}
private:
list<pair<int, int>> entries;
unordered_map<int, list<pair<int, int>>::iterator> table;
int capacity;
};