-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode146.cpp
More file actions
97 lines (68 loc) · 1.63 KB
/
leetcode146.cpp
File metadata and controls
97 lines (68 loc) · 1.63 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class LRUCache {
public:
class Node{
public:
int key,val;
Node* prev;
Node* next;
Node(int k,int v){
key = k;
val =v;
prev = next = NULL;
}
};
Node* head =new Node(-1,-1);
Node* tail = new Node(-1,-1);
unordered_map<int ,Node*> m;
void addNode(Node* newNode){
Node* oldNext = head->next;
head->next = newNode;
oldNext->prev =newNode;
newNode->prev = head;
newNode->next =oldNext;
}
void delNode(Node* oldNode){
Node* oldprev = oldNode->prev;
Node* oldnext = oldNode->next;
oldprev->next =oldnext;
oldnext->prev = oldprev;
}
int limit;
LRUCache(int capacity) {
limit =capacity;
head->next =tail;
tail->prev = head;
}
int get(int key) {
if(m.find(key)==m.end()){
return -1;
}
Node* ansNode=m[key];
int ans =ansNode->val;
m.erase(key);
delNode(ansNode);
addNode(ansNode);
m[key] =ansNode;
return ans;
}
void put(int key, int value) {
if(m.find(key)!=m.end()){
Node* oldNode =m[key];
delNode(oldNode);
m.erase(key);
}
if(m.size()==limit){
m.erase(tail->prev->key);
delNode(tail->prev);
}
Node* newNode = new Node(key,value);
addNode(newNode);
m[key] = newNode;
}
};
/**
* 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);
*/