leetcode 146. LRU Cache
来源:互联网 发布:mac卸载软件残留 编辑:程序博客网 时间:2024/05/17 05:02
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
class LRUCache{struct Node{int val;int key;Node*pre, *nxt;Node(int x) :val(x){pre = NULL;nxt = NULL;}};int capa;int cursize;Node*head;Node*tail;unordered_map<int, Node*>keymap;public:~LRUCache(){for (unordered_map<int, Node*>::iterator it = keymap.begin(); it != keymap.end(); it++)delete it->second;}LRUCache(int capacity) {capa = capacity;head = NULL;tail = NULL;cursize = 0;}int get(int key) {if (capa > 0){unordered_map<int, Node*>::iterator it = keymap.find(key);if (it == keymap.end())return -1;Node*pre = it->second->pre;Node*nxt = it->second->nxt;if (pre != NULL){if (it->second == tail)tail = pre;pre->nxt = nxt;if (nxt!=NULL)nxt->pre = pre;it->second->nxt = head;head->pre = it->second;it->second->pre = NULL;head = it->second;}return it->second->val;}return -1;}void set(int key, int value) {if (capa > 0){unordered_map<int, Node*>::iterator it = keymap.find(key);if (it == keymap.end()){if (cursize == capa){keymap.erase(keymap.find(tail->key));tail->key = key;tail->val = value;keymap[key] = tail;if (head != tail){Node*pre = tail->pre;pre->nxt = NULL;tail->nxt = head;head->pre = tail;head = tail;head->pre = NULL;tail = pre;}}else{Node*n = new Node(value);n->key = key;if (head == NULL){head = n;tail = n;}else{n->nxt = head;head->pre = n;head = n;}keymap[key] = n;cursize++;}}else{Node*pre = it->second->pre;Node*nxt = it->second->nxt;if (pre != NULL){if (it->second == tail)tail = pre;pre->nxt = nxt;if (nxt != NULL)nxt->pre = pre;it->second->nxt = head;head->pre = it->second;it->second->pre = NULL;head = it->second;}it->second->val = value;}}}};
accept
0 0
- 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
- 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
- Json与javaBean之间的转换工具类
- 用 JavaScript 对抗 DDOS 攻击
- hdoj 2602 Bone Collector【裸0-1背包】
- 读[查询优化改写 技巧与案例]一书有感
- 详细介绍VO和PO的区别
- leetcode 146. LRU Cache
- 对于大学4年的反思(续),记我的ThoughtWorks面试
- 题目1089:数字反转
- 中断与轮询
- memcached实战系列(三)memcached命令使用
- JavaScript 模块(1):初学者指南
- 说说JavaScript那些事
- CSS实现垂直居中的常用方法
- 一个jQuery事件绑定的问题