Leetcode 146. LRU 缓存机制
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 146. LRU 缓存机制
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原題鏈接
題解:雙鏈表+哈希表
class LRUCache { public:struct Node {int key, val;Node *left, *right;Node(int _key, int _val): key(_key), val(_val), left(NULL), right(NULL) {}}*L, *R;unordered_map<int, Node*> hash;int n;void remove(Node* p) {p->right->left = p->left;p->left->right = p->right;}void insert(Node* p) {p->right = L->right;p->left = L;L->right->left = p;L->right = p;}LRUCache(int capacity) {n = capacity;L = new Node(-1, -1), R = new Node(-1, -1);L->right = R, R->left = L;}int get(int key) {if (hash.count(key) == 0) return -1;auto p = hash[key];remove(p);insert(p);return p->val;}void put(int key, int value) {if (hash.count(key)) {auto p = hash[key];p->val = value;remove(p);insert(p);} else {if (hash.size() == n) {auto p = R->left;remove(p);hash.erase(p->key);delete p;}auto p = new Node(key, value);hash[key] = p;insert(p);}} };/*** 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);*/?
總結(jié)
以上是生活随笔為你收集整理的Leetcode 146. LRU 缓存机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: udp linux协议栈流程(udp l
- 下一篇: linux的虚拟机安装(linux的虚拟