leetcode 146: LRU Cache
来源:互联网 发布:逍遥安卓无法连接网络 编辑:程序博客网 时间:2024/06/06 19:12
Use an unordered map and a doubly linked list to implement.
struct Node{ int key; int value; Node* next; Node* pre; Node(int k,int v){ key=k; value=v; pre=next=NULL; }};class LRUCache{public: LRUCache(int capacity) { cap=capacity; cachesize=0; head=new Node(0,0); tail=new Node(0,0); head->next=tail; tail->pre=head; } int get(int key) { if(mp.find(key)!=mp.end()) { Node *p=mp[key]; p->next->pre=p->pre; p->pre->next=p->next; p->pre=tail->pre; tail->pre->next=p; p->next=tail; tail->pre=p; return mp[key]->value; } return -1; } void set(int key, int value) { unordered_map<int,Node*>::iterator it=mp.find(key); if(it!=mp.end()) { Node *p=mp[key]; p->next->pre=p->pre; p->pre->next=p->next; p->value=value; p->pre=tail->pre; tail->pre->next=p; p->next=tail; tail->pre=p; } else { if(cachesize==cap) { it=mp.find(head->next->key); Node *p=head->next; head->next->next->pre=head; head->next=head->next->next; delete p; mp.erase(it); cachesize--; } Node *p=new Node(key,value); p->pre=tail->pre; tail->pre->next=p; p->next=tail; tail->pre=p; mp.insert(make_pair(key,p)); cachesize++; } }private: unordered_map<int,Node*> mp; Node* head; Node* tail; int cachesize; int cap;};
0 0
- LeetCode: LRU Cache [146]
- LeetCode 146 LRU Cache
- LeetCode(146) LRU Cache
- leetcode || 146、LRU Cache
- leetcode 146: LRU Cache
- LeetCode 146 LRU Cache
- LeetCode -146 LRU Cache
- LeetCode 146 LRU Cache
- Leetcode 146 LRU Cache
- Leetcode 146 LRU Cache 模拟操作系统LRU
- 【Leetcode-hard-146】LRU Cache
- LeetCode LRU 缓存 LRU Cache
- leetcode 146 —— LRU Cache
- solution of LeetCode:146 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- mac 下作流程图工具omnigraffle
- 解决php中截取字符串的中文乱码问题
- ListView的使用
- android 我遇到的问题
- Firebug折腾记_(2)HTML&CSS定位及调试小技巧
- leetcode 146: LRU Cache
- view获取父类控制器
- POJ1144--Network(Tarjan求割点)
- Linux--Sys_Read系统调用过程分析
- 20_ java.lang.IllegalArgumentException: Service Intent must be explicit异常说明
- 再谈子数组/子串问题
- [设计模式] - 创建型模式
- 作为一个新人,怎样学习嵌入式Linux?(韦东山)
- 配置免安装版的mysql