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
| class LRUCache { public:
struct Node { int key, val; Node *next, *prev; Node(int _key, int _val): key(_key), val(_val), next(nullptr), prev(nullptr) {}; } *L, *R;
unordered_map<int, Node*> hash; int n;
LRUCache(int capacity) { n = capacity; L = new Node(-1, -1), R = new Node(-1, -1); L->next = R, R->prev = L; }
void insert_node(Node *p) { p->next = L->next, L->next->prev = p, p->prev = L, L->next = p; }
void delete_node(Node *p) { p->next->prev = p->prev, p->prev->next = p->next; } int get(int key) { if (hash.count(key)) { auto p = hash[key]; delete_node(p); insert_node(p); return p->val; } else { return -1; } } void put(int key, int value) { if (hash.count(key)) { auto p = hash[key]; delete_node(p); p->val = value; insert_node(p); } else { if (n == hash.size()) { auto q = R->prev; delete_node(q); hash.erase(q->key); } auto p = new Node(key, value); hash[key] = p; insert_node(p); } } };
|