题目:

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. 复习一下xml(c)

    简单介绍 Using System.Xml; XMLDocument xml=new XmlDocument();xml.Load(path);//初始化一个实例 xml.Load(HttpConte ...

  2. Home Assistant + 树莓派:强大的智能家居系统 · 安装篇

    Home Assistant + 树莓派:强大的智能家居系统 · 安装篇 转载:Home Assistant + 树莓派:强大的智能家居系统 · 安装篇 目录 1. 初始安装 3. Homebridg ...

  3. Python2字符编码问题汇总

    目录 从字符编码说起 unicode与utf-8 当编解码遇上Python2.x unicode 与 str 区别 __str__ __repr__的区别 unicode str utf-8关系 un ...

  4. 深入理解ajax系列第九篇

    前面的话 jQuery提供了一些日常开发中需要的快捷操作,例如load.ajax.get和post等,使用jQuery开发ajax将变得极其简单.这样开发人员就可以将程序开发集中在业务和用户体验上,而 ...

  5. BeautifulSoup与Xpath解析库总结

    一.BeautifulSoup解析库 1.快速开始 html_doc = """ <html><head><title>The Dor ...

  6. ThinkPHP3.2设置异常页面404跳转页面

    在ThinkPHP3.2版本中当我们访问不存在的页面时会出现非常不友好错误提示页面,类如下图: 0 «上一篇:div非弹出框半透明遮罩实现全屏幕遮盖css实现»下一篇:利于反向代理绑定任意的域名 po ...

  7. NOIP2018 生气记

    今年的题都不怎么难 只是考到的东西相当相当的奇怪... 不想写题解,写出来感觉只是伤心的事 .................... Day1 一进考场就感受到了比去年要严一些... 花了1小时30分 ...

  8. BZOJ 3483 SGU505 Prefixes and suffixes(字典树+可持久化线段树)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3483 [题目大意] 给出一些串,同时给出m对前缀后缀,询问有多少串满足给出的前缀后缀模 ...

  9. hdu 4545 贪心 *

    题意:小明和他的好朋友小西在玩一个新的游戏,由小西给出一个由小写字母构成的字符串,小明给出另一个比小西更长的字符串,也由小写字母组成,如果能通过魔法转 换使小明的串和小西的变成同一个,那么他们两个人都 ...

  10. Codeforces Round #298 (Div. 2) B. Covered Path 物理题/暴力枚举

    B. Covered Path Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/534/probl ...