题目:

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. 【知了堂学习笔记】java IO流归纳总结

    皮皮潇最近学到了IO流但是感觉这一块要记的东西太多了,所以重API上查阅并总结了以下几点关于IO的知识. 1.File(文件类): File类是文件以及文件夹进行封装的对象,用对象的思想来操作文件和文 ...

  2. 有了这套flex页面布局方案,页面什么的,那都不是事。

    一.CSS3弹性盒子弹性盒子是CSS3的一种新布局模式.CSS3 弹性盒( Flexible Box 或 flexbox),是一种当页面需要适应不同的屏幕大小以及设备类型时确保元素拥有恰当的行为的布局 ...

  3. 不要62 hdu 2089 dfs记忆化搜索

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2089 题意: 给你两个数作为一个闭区间的端点,求出该区间中不包含数字4和62的数的个数 思路: 数位dp中 ...

  4. MSTP多生成树的配置

    STP的不足 STP协议虽然能够解决环路问题,但是由于网络拓扑收敛较慢,影响了用户通信质量 而且如果网络中的拓扑结构频繁变化,网络也会随之频繁失去连通性,从而导致用户通信频繁中断 RSTP对STP的改 ...

  5. 使用UniBeast安装Hackintosh(黑苹果)

    前期准备 UniBeast 原版macOS Sierra安装包,由于苹果并没有提供完整dmg的下载地址,我也不在此提供,大家可以从信任的途径取得,文件后缀必须为dmg. 16GB或者更大的U盘 至少2 ...

  6. 你见过这些JavaScript的陷阱吗?

    一.成员操作符 Number.prototype.testFn=function () { console.log(this<0, this.valueOf()); } var num = -1 ...

  7. 浏览器在线查看pdf文件 pdf.js的使用教程

    谷歌浏览器可以直接在线查看pdf,而IE内核浏览器无法在线查看,默认是下载. 这里用到的是pdf.js,不仅支持IE内核浏览器,而且兼容手机查看pdf 官网地址:http://mozilla.gith ...

  8. bzoj 3211 线段树

    开方操作最多进行5次就可以把出现的任何数变成1. 所以用线段树暴力修改,以后修改时只需看一下是否当前区间都是0或1,如果是那么就直接返回. /***************************** ...

  9. nodejs环境使用jshint

    一.概述jshint是检测JavaScript语法问题的工具,可以根据自己的需要配置检测规则. 二.安装npm install jshint -g一般全局安装就可以了,可以在任何目录下使用jshint ...

  10. ubuntu 自动获取ip

    $sudo dhclient -r $sudo dhclient $sudo dhclient eth0