LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
哈希+双链表
#include <iostream> #include <unordered_map> using namespace std; struct Node { int value; int key; Node *next; Node *pre; Node() : key(0), value(0), next(nullptr), pre(nullptr) {}; Node(int key, int val) : key(key), value(val), next(nullptr), pre(nullptr) {}; ~Node(); }; class LRUCache { private: unordered_map<int, Node *> cache; int size; int cap; Node *head; Node *tail; public: LRUCache(int capacity) : cap(capacity), size(0) { head = new Node(-1, -1); tail = new Node(10, 10); head->next = tail; tail->pre = head; } int get(int key) { auto ele = cache.find(key); if (ele != cache.end()) { Node *eleNode = ele->second; gotail(eleNode); return eleNode->value; } else return -1; } void put(int key, int value) { auto ele = cache.find(key); if (ele != cache.end()) { //the key is existed Node *eleNode = ele->second; eleNode->value = value; gotail(eleNode); } else { //the key is not existed Node *nd = new Node(key, value); cache.insert(pair<int, Node *>{key, nd}); Node *tail_pre = tail->pre; nd->pre = tail_pre; tail_pre->next = nd; nd->next = tail; tail->pre = nd; size++; while (size > cap) { Node *removedNode = head->next; removedNode->next->pre = head; head->next = removedNode->next; cache.erase(removedNode->key); size--; } } } void gotail(Node *nd) { nd->next->pre = nd->pre; nd->pre->next = nd->next; Node *tail_pre = tail->pre; tail_pre->next = nd; nd->pre = tail_pre; tail->pre = nd; nd->next = tail; } }; int main() { LRUCache *obj = new LRUCache(2); obj->put(1, 1); obj->put(2, 2); int param_1 = obj->get(1); cout << param_1 << endl; obj->put(3, 3); int param_2 = obj->get(2); cout << param_2 << endl; obj->put(4, 4); int param_3 = obj->get(3); cout << param_3 << endl; int param_4 = obj->get(4); cout << param_4 << endl; }
浙公网安备 33010602011771号