题目:

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.

题解:

这道题是一个数据结构设计题,在leetcode里面就这么一道,还是挺经典的一道题,可以好好看看。

这道题要求设计实现LRU cache的数据结构,实现set和get功能。学习过操作系统的都应该知道,cache作为缓存可以帮助快速存取数据,但是确定是容量较小。这道题要求实现的cache类型是LRU,LRU的基本思想就是“最近用到的数据被重用的概率比较早用到的大的多”,是一种更加高效的cache类型。

解决这道题的方法是:双向链表+HashMap

“为了能够快速删除最久没有访问的数据项和插入最新的数据项,我们将双向链表连接Cache中的数据项,并且保证链表维持数据项从最近访问到最旧访问的顺序
每次数据项被查询到时,都将此数据项移动到链表头部(O(1)的时间复杂度)。这样,在进行过多次查找操作后,最近被使用过的内容就向链表的头移动,而没
有被使用的内容就向链表的后面移动。当需要替换时,链表最后的位置就是最近最少被使用的数据项,我们只需要将最新的数据项放在链表头部,当Cache满
时,淘汰链表最后的位置就是了。 ”

“注: 对于双向链表的使用,基于两个考虑。

首先是Cache中块的命中可能是随机的,和Load进来的顺序无关。

其次,双向链表插入、删除很快,可以灵活的调整相互间的次序,时间复杂度为O(1)。”

解决了LRU的特性,现在考虑下算法的时间复杂度。为了能减少整个数据结构的时间复杂度,就要减少查找的时间复杂度,所以这里利用HashMap来做,这样时间苏咋读就是O(1)。

所以对于本题来说:

get(key): 如果cache中不存在要get的值,返回-1;如果cache中存在要找的值,返回其值并将其在原链表中删除,然后将其作为头结点。

set(key,value):当要set的key值已经存在,就更新其value, 将其在原链表中删除,然后将其作为头结点;当药set的key值不存在,就新建一个node,如果当前len<capacity,就将其加入hashmap中,并将其作为头结点,更新len长度,否则,删除链表最后一个node,再将其放入hashmap并作为头结点,但len不更新。

原则就是:对链表有访问,就要更新链表顺序。

代码如下:

 1     private HashMap<Integer, DoubleLinkedListNode> map 
 2         = new HashMap<Integer, DoubleLinkedListNode>();
 3     private DoubleLinkedListNode head;
 4     private DoubleLinkedListNode end;
 5     private int capacity;
 6     private int len;
 7  
 8     public LRUCache(int capacity) {
 9         this.capacity = capacity;
         len = 0;
     }
  
     public int get(int key) {
         if (map.containsKey(key)) {
             DoubleLinkedListNode latest = map.get(key);
             removeNode(latest);
             setHead(latest);
             return latest.val;
         } else {
             return -1;
         }
     }
  
     public void removeNode(DoubleLinkedListNode node) {
         DoubleLinkedListNode cur = node;
         DoubleLinkedListNode pre = cur.pre;
         DoubleLinkedListNode post = cur.next;
  
         if (pre != null) {
             pre.next = post;
         } else {
             head = post;
         }
  
         if (post != null) {
             post.pre = pre;
         } else {
             end = pre;
         }
     }
  
     public void setHead(DoubleLinkedListNode node) {
         node.next = head;
         node.pre = null;
         if (head != null) {
             head.pre = node;
         }
  
         head = node;
         if (end == null) {
             end = node;
         }
     }
  
     public void set(int key, int value) {
         if (map.containsKey(key)) {
             DoubleLinkedListNode oldNode = map.get(key);
             oldNode.val = value;
             removeNode(oldNode);
             setHead(oldNode);
         } else {
             DoubleLinkedListNode newNode = 
                 new DoubleLinkedListNode(key, value);
             if (len < capacity) {
                 setHead(newNode);
                 map.put(key, newNode);
                 len++;
             } else {
                 map.remove(end.key);
                 end = end.pre;
                 if (end != null) {
                     end.next = null;
                 }
  
                 setHead(newNode);
                 map.put(key, newNode);
             }
         }
     }
 }
  
 class DoubleLinkedListNode {
     public int val;
     public int key;
     public DoubleLinkedListNode pre;
     public DoubleLinkedListNode next;
  
     public DoubleLinkedListNode(int key, int value) {
         val = value;
         this.key = key;
     }

Reference:

1. http://blog.csdn.net/hexinuaa/article/details/6630384
(引号中字引自此处)
2. http://www.cnblogs.com/feiling/p/3426967.html

3. http://www.programcreek.com/2013/03/leetcode-lru-cache-java/ (代码参考)

LRU Cache leetcode java的更多相关文章

  1. LRU Cache [LeetCode]

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  2. 如何设计一个LRU Cache

    如何设计一个LRU Cache? Google和百度的面试题都出现了设计一个Cache的题目,什么是Cache,如何设计简单的Cache,通过搜集资料,本文给出个总结. 通常的问题描述可以是这样: Q ...

  3. Java for LeetCode 146 LRU Cache 【HARD】

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  4. LeetCode – LRU Cache (Java)

    Problem Design and implement a data structure for Least Recently Used (LRU) cache. It should support ...

  5. leetcode 146. LRU Cache ----- java

    esign and implement a data structure for Least Recently Used (LRU) cache. It should support the foll ...

  6. LeetCode之LRU Cache 最近最少使用算法 缓存设计

    设计并实现最近最久未使用(Least Recently Used)缓存. 题目描述: Design and implement a data structure for Least Recently ...

  7. 【LeetCode】LRU Cache 解决报告

    插话:只写了几个连续的博客,博客排名不再是实际"远在千里之外"该.我们已经进入2一万内. 再接再厉.油! Design and implement a data structure ...

  8. [LeetCode] 146. LRU Cache 近期最少使用缓存

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  9. LeetCode题解: LRU Cache 缓存设计

    LeetCode题解: LRU Cache 缓存设计 2014年12月10日 08:54:16 邴越 阅读数 1101更多 分类专栏: LeetCode   版权声明:本文为博主原创文章,遵循CC 4 ...

随机推荐

  1. poj-3268最短路

    title: poj-3268最短路 date: 2018-10-13 15:54:34 tags: acm 刷题 categories: ACM-最短路 概述 这是一道最短路的模板题,,,不过虽然是 ...

  2. (视频)asp.net core系列之k8s集群部署视频

    0.前言 应许多网友的要求,特此录制一下k8s集群部署的视频.在录制完成后发现视频的声音存在一点瑕疵,不过不影响大家的观感. 一.视频说明 1.视频地址: 如果有不懂,或者有疑问的欢迎留言.视频分为两 ...

  3. 机器学习之路:python 多项式特征生成PolynomialFeatures 欠拟合与过拟合

    分享一下 线性回归中 欠拟合 和 过拟合 是怎么回事~为了解决欠拟合的情 经常要提高线性的次数建立模型拟合曲线, 次数过高会导致过拟合,次数不够会欠拟合.再建立高次函数时候,要利用多项式特征生成器 生 ...

  4. 【洛谷】2324:[SCOI2005]骑士精神【IDA*】

    P2324 [SCOI2005]骑士精神 题目描述 输入输出格式 输入格式: 第一行有一个正整数T(T<=10),表示一共有N组数据.接下来有T个5×5的矩阵,0表示白色骑士,1表示黑色骑士,* ...

  5. 使用TensorFlow高级别的API进行编程

    这里涉及到的高级别API主要是使用Estimator类来编写机器学习的程序,此外你还需要用到一些数据导入的知识. 为什么使用Estimator Estimator类是定义在tf.estimator.E ...

  6. "Blessing of Dimisionality: High Dimensional Feature and Its Efficient Compression for Face Verification"学习笔记

    这\(^{[1]}\)是一篇关于如何使用高维度特征在人脸验证中的文章,作者以主要LBP为例子,论述了高维特征和验证性能存在着正相关的关系,即人脸维度越高,验证的准确度就越高.由于那时候没有用DeepL ...

  7. tomcat-调整内存参数

    查看Tomcat的默认内存参数: <% /; /; /; out.println("max="+max); out.println("total="+to ...

  8. Hibernate3 jar包的作用[转]

    from:http://nopainnogain.iteye.com/blog/761630 (1)hibernate3.jar: Hibernate的核心库,没有什么可说的,必须使用的jar包 (2 ...

  9. JS仿淘宝左侧菜单

    http://www.webdm.cn/webcode/1c724a06-06f4-4c4f-931a-c683285fa700.html

  10. Maven最佳实践 划分模块 配置多模块项目 pom modules

    所有用Maven管理的真实的项目都应该是分模块的,每个模块都对应着一个pom.xml.它们之间通过继承和聚合(也称作多模块,multi-module)相互关联.那么,为什么要这么做呢?我们明明在开发一 ...