LRU Cache -- LeetCode
2016-01-28 12:45
323 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
思路:使用哈希表来记录key与值。为了实现LRU,我们需要实现一个双向链表,最少使用的在链表头,最近使用的在链表尾。对于每一个key,我们还需要一个哈希表来记录它在该链表中的地址。
在代码实现过程中,新申请一个链表只能用new的形式来申请,该语句将返回一个申请后的指针。
getand
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.
思路:使用哈希表来记录key与值。为了实现LRU,我们需要实现一个双向链表,最少使用的在链表头,最近使用的在链表尾。对于每一个key,我们还需要一个哈希表来记录它在该链表中的地址。
在代码实现过程中,新申请一个链表只能用new的形式来申请,该语句将返回一个申请后的指针。
class LRUCache{ public: class dlist { public: dlist *pre, *next; int key; dlist(int d, dlist *p, dlist *f) : key(d), pre(p), next(f){} }; int cap; dlist *front, *tail; unordered_map<int, int> data; unordered_map<int, dlist *> addr; LRUCache(int capacity) { cap = capacity; front = new dlist(0, NULL, NULL); tail = new dlist(0, NULL, NULL); front->next = tail; tail->pre = front; } int get(int key) { if (data.count(key) == 0) return -1; Delete(addr[key]); AddtoTail(addr[key]); return data[key]; } void AddtoTail(dlist *node) { tail->pre->next = node; node->pre = tail->pre; node->next = tail; tail->pre = node; } void Delete(dlist *node) { node->pre->next = node->next; node->next->pre = node->pre; } void set(int key, int value) { if (data.size() == cap && data.count(key) == 0) { if (front->next == tail) return; data.erase(front->next->key); addr.erase(front->next->key); Delete(front->next); } if (data.count(key) == 0) { data.insert(make_pair(key, value)); dlist *ent = new dlist(key, NULL, NULL); addr.insert(make_pair(key, ent)); AddtoTail(ent); } else { data[key] = value; Delete(addr[key]); AddtoTail(addr[key]); } } };
相关文章推荐
- C# 16进制与字符串、字节数组之间的转换
- 陌陌凭什么排中国iOS收入榜社交第一?无需惊奇
- Spring 源码分析(一) —— 迈向Spring之路
- iOS去除icon图标特效,阴影,反光
- HashSet的实现,与hashMap的关系
- docker学习(4) 一些常用操作
- 如何添加Admob
- LeetCode AddDigits
- C++中cin、cin.get()、cin.getline()、getline()、gets()等
- 【NOIP模拟题】日历游戏
- [LeetCode] Patching Array 补丁数组
- 网络爬虫介绍(待完善)
- QTextEdit实现语法高亮-Syntax Highlighter Example例子简单介绍
- hdu 1024 Max Sum Plus Plus(动态规划+m子段和的最大值)
- crc32校验48位mac 地址
- linux内核启动流程分析
- [解析苹果官方文档]之[UIView Class Reference]
- 数组
- 测试设计中需要考虑的22种测试类型
- 二叉排序树(创建,查找,删除)