博客
关于我
leetcode-146. LRU 缓存机制
阅读量:246 次
发布时间:2019-03-01

本文共 1729 字,大约阅读时间需要 5 分钟。

在这里插入图片描述

核心,哈希表+双向链表
分类:

  • 添加节点(缓存未满)
  • 移除节点,添加节点(缓存满)
  • 更新节点(已有节点)

在get的时候断开节点得到独立节点,将节点放到head后面

在这里插入图片描述

class LRUCache {   public:    int capacity_,idle_;    struct Node{           int key_,val_;        Node* next;        Node* pre;        Node(int key,int val):key_(key),val_(val),next(NULL),pre(NULL){   }    };    Node* head=new Node(-1,-1);    Node* tail=new Node(-1,-1);    unordered_map
memo; LRUCache(int capacity):idle_(capacity),capacity_(capacity) { head->next=tail; tail->pre=head; } void putHead(Node* node){ node->next=head->next; node->pre=head; head->next->pre=node; head->next=node; } int get(int key) { if(memo.find(key)==memo.end()) return -1; memo[key]->next->pre=memo[key]->pre; memo[key]->pre->next=memo[key]->next; putHead(memo[key]); return memo[key]->val_; } void put(int key, int value) { if(memo.find(key)==memo.end()&&idle_>0){ idle_--; Node* node=new Node(key,value); memo[key]=node; } else if(memo.find(key)==memo.end()&&idle_==0){ Node* node=tail->pre; node->next->pre=node->pre; node->pre->next=node->next; memo.erase(node->key_); node->val_=value; node->key_=key; memo[key]=node; } else if(memo.find(key)!=memo.end()&&memo[key]!=NULL){ memo[key]->val_=value; memo[key]->next->pre=memo[key]->pre; memo[key]->pre->next=memo[key]->next; } putHead(memo[key]); // cout<
next->key_<
next->val_<
get(key); * obj->put(key,value); */

转载地址:http://kqav.baihongyu.com/

你可能感兴趣的文章
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>