LeetCode解题报告:LRU Cache
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.
思路:Java的LinkedHashMap可以实现最近最少使用(LRU)的次序。类似于HashMap。详见《JAVA编程思想(第4版)》P487.
题目要求是一个固定大小的cache,因此需要一个变量maxCapacity来记录容量大小,用LinkedHashMap存储数据。在添加数据set()方法时,判断一下是否达到maxCapacity,如果cache已经满了,remove掉最长时间不使用的数据,然后put进新的数据。
注意:HashMap,LinkedHashMap,TreeMap的区别,详细看看StackOverFlow
LinkedHashMap最常用的是LRU cache的实现。
如果用C++实现的话, hashmap + 双向链表:用 双向链表记录value 用hashmap记录 key值在链表中的位置(指针)。
unordered_map<int, list<CacheNode>:: iterator> cacheMap;
题解:
import java.util.LinkedHashMap;
public class LRUCache {
LinkedHashMap<Integer, Integer> linkedmap;
int maxCapacity;
public LRUCache(int capacity) {
this.maxCapacity = capacity;
this.linkedmap = new LinkedHashMap<Integer, Integer>(capacity, 1f, true);
}
public int get(int key) {
if (linkedmap.containsKey(key))
return linkedmap.get(key);
else
return -1;
}
public void set(int key, int value) {
int size = linkedmap.size();
if ((size < maxCapacity) || (linkedmap.containsKey(key))) {
linkedmap.put(key, value);
} else if (size >= maxCapacity) {
Iterator<Integer> it = linkedmap.keySet().iterator();//iterator method is superior the toArray(T[] a) method.
linkedmap.remove(it.next());
linkedmap.put(key, value);
}
}
}
结题遇到的问题:
1.下面这段代码提交的时候超时了。
import java.util.LinkedHashMap;
public class LRUCache {
LinkedHashMap<Integer, Integer> linkedmap;
int maxCapacity;
public LRUCache(int capacity) {
this.maxCapacity = capacity;
this.linkedmap = new LinkedHashMap<Integer, Integer>(capacity, 1f, true);
}
public int get(int key) {
if (linkedmap.containsKey(key))
return linkedmap.get(key);
else
return -1;
}
public void set(int key, int value) {
int size = linkedmap.size();
if ((size < maxCapacity) || (linkedmap.containsKey(key))) {
linkedmap.put(key, value);
} else if (size >= maxCapacity) {
Integer[] keyArray = linkedmap.keySet().toArray(new Integer[0]);//这是超时的代码,采用Iterator不会超时。
linkedmap.remove(keyArray[0]);
linkedmap.put(key, value);
}
}
}
2.Roger自己实现LinkedHashMap的功能,采用双向链表和哈希表。效率略低于LinkedHashMap.(644ms>548ms)
import java.util.HashMap;
public class LRUCache {
private HashMap<Integer, Entry<Integer>> index;
private UDFList<Integer> data;
public LRUCache(int capacity) {
index = new HashMap<Integer, Entry<Integer>>(capacity);
data = new UDFList<Integer>(capacity);
}
public int get(int key) {
if (!isExist(key)) {
index.remove(key);
return -1;
}
if (!index.get(key).equals(data.head)) {
Entry<Integer> nodePtr = data.adjust(index.get(key));
index.put(key, nodePtr);
}
return index.get(key).element;
}
public void set(int key, int value) {
if (isExist(key)) {
data.remove(index.get(key));
}
index.put(key, data.push(value));
}
private boolean isExist(int key) {
if (index.get(key) == null) {
return false;
}
if (index.get(key).element == null) {
return false;
}
return true;
}
public class UDFList<E> {
public Entry<E> head;
public Entry<E> tail;
public final int size;
public int length = 0;
public UDFList(int size) {
head = new Entry<E>(null, null, null);
tail = head;
this.size = size;
}
public Entry<E> adjust(Entry<E> node) {
if (node.equals(tail)) {
tail = tail.previous;
tail.next = null;
node.previous = null;
} else if (node.equals(head)) {
node = null;
return head;
} else {
node.previous.next = node.next;
node.next.previous = node.previous;
}
head.previous = node;
node.next = head;
head = node;
node = null;
return head;
}
public Entry<E> push(E e) {
Entry<E> newNode = new Entry<E>(e, null, null);
if (length == 0) {
head = newNode;
tail = head;
} else {
head.previous = newNode;
newNode.next = head;
head = newNode;
}
if (length == size) {
remove(tail);
}
length++;
return head;
}
public void remove(Entry<E> node) {
if (node == null)
return;
node.element = null;
if (node.equals(head)) {
head = head.next;
} else if (node.equals(tail)) {
tail = tail.previous;
tail.next = null;
} else {
node.previous.next = node.next;
node.next.previous = node.previous;
}
node = null;
length--;
}
}
public class Entry<E> {
public E element;
public Entry<E> previous;
public Entry<E> next;
public Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
}
LeetCode解题报告:LRU Cache的更多相关文章
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- LeetCode题解: LRU Cache 缓存设计
LeetCode题解: LRU Cache 缓存设计 2014年12月10日 08:54:16 邴越 阅读数 1101更多 分类专栏: LeetCode 版权声明:本文为博主原创文章,遵循CC 4 ...
- 【LeetCode】146. LRU Cache 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典+双向链表 日期 题目地址:https://le ...
- LRU算法&&LeetCode解题报告
题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- 【LeetCode OJ】LRU Cache
Problem Link: http://oj.leetcode.com/problems/lru-cache/ Long long ago, I had a post for implementin ...
- 【LeetCode】146. LRU Cache
LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should suppo ...
- LeetCode OJ:LRU Cache(最近使用缓存)
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
随机推荐
- MSDN Webcast 系列课程
云计算(Cloud) 云起龙骧系列课程 网络开发(Web) ASP.NET 4 风云之旅系列课程 ASP.NET 开发实践系列课程 MOSS2007 最佳实战 StepByStep 系列课程 Silv ...
- readonly时禁用删除键,readonly按删除键后页面后退解决方案
readonly时禁用删除键, readonly按删除键后页面后退解决方案 >>>>>>>>>>>>>>>&g ...
- day-8
/* 倒数8天了 今天高考报名 两个班主任都来了23333 然后填班主任姓名就尴尬了23333 上午考试 挺不错的题目 都不是很水 但需要思考 而我是一脸的懵逼~~ 下午整理各种板子 主要是图论的 最 ...
- PS之放射背景
效果图 素材 新建图层,填充颜色 新建图层,矩形工具画条形 滤镜-扭曲-极坐标 合并图层,效果如下 新建图层,画一个适当的圆 滤镜-模糊-高斯模糊 将素材人物抠出来放在中间
- in 与 = 的区别
in 与 = 的区别 结果是相同的.
- MICROSOFT REPORT VIEWER 2012之无法加载相关的dll
使用VS 2012开发报表, 如果是使用的微软的报表控件的话,默认是使用的MICROSOFT REPORT VIEWER 2012,本地开发基本上没问题,但是一发布服务器,就会发现坑了,微软挖坑从来就 ...
- 浅析Activity不可见与透明
http://blog.csdn.net/lincyang/article/details/6868582 看见标题也许你会有疑问,不可见和透明不是一个意思吗? 从字面上看,这还真是差不多.但在Act ...
- Oracle 11g-R2 SQL Developer连接MSSQL2008
操作系统环境:WINDOWS8.1 工具: Oracle 11g-R2 SQL Developer 网络资源:http://sourceforge.net/project/showfiles.php ...
- Object-C — KVC
1:使用kvc存取对象属性 如果要更改对象属性可以通过什么方法达到呢? (1)通过setter和getter方法. (2)属性. (3)直接设置实例变量. 今天学习新的一种方法:键值编码-kvc.通过 ...
- jfreechart环形图完美实现
邮件发送由于不支持js,项目只能在后台生成环形图,用jfreechart完全可以实现,即:RingPlot. 这就拿jfreechart生成的最终效果,依赖jar包jfreechart,如果有任何细节 ...