-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.lru-cache.cpp
More file actions
109 lines (103 loc) · 2.14 KB
/
146.lru-cache.cpp
File metadata and controls
109 lines (103 loc) · 2.14 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
98
99
100
101
102
103
104
105
106
107
108
109
/*
* @lc app=leetcode id=146 lang=cpp
*
* [146] LRU Cache
*/
#include <vector>
#include <map>
using namespace std;
// @lc code=start
class LRUCache
{
public:
typedef struct node
{
int key;
int value;
node *prev;
node *next;
} node;
int cap;
map<int, node *> nodes;
node *head;
node *tail;
bool full;
LRUCache(int capacity)
{
nodes = map<int, node *>();
cap = capacity;
head = new node{-1, -1, nullptr, nullptr};
tail = new node{-1, -1, nullptr, nullptr};
tail->prev = head;
head->next = tail;
full = false;
}
int get(int key)
{
if (nodes.find(key) == nodes.end())
{
return -1;
}
node *n = unlink(key);
append(n);
int value = n->value;
return value;
}
void put(int key, int value)
{
node *n = nullptr;
// key in map
if (nodes.find(key) != nodes.end())
{
// unlink
n = unlink(key);
n->value = value;
}
else
{
if (full)
{
// full
// ecivt node first
int del_key = head->next->key;
unlink(del_key);
nodes.erase(del_key);
}
n = new node{
key,
value,
nullptr,
nullptr,
};
}
append(n);
if (!full && nodes.size() == cap)
{
full = true;
}
}
void append(node *n)
{
n->prev = tail->prev;
n->next = tail;
tail->prev->next = n;
tail->prev = n;
nodes[n->key] = n;
}
node *unlink(int key)
{
node *n = nodes[key];
n->prev->next = n->next;
n->next->prev = n->prev;
n->prev = nullptr;
n->next = nullptr;
return n;
}
};
/**
* 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);
*/
// @lc code=end