题目:

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. SELECT INTO和INSERT INTO SELECT(SQL Server)

    --自动创建了target_table表,并复制source_table表的数据到target_table select name,age into target_table from source_ ...

  2. 某谷 P5153 简单的函数

    题面在这里 个人感觉这个题可以被打表随便艹过,当然我不是这么做的... 虽然n可达10^18,但随便分析一下就可以发现f(n)是极小的,因为f(n)一步就可以跳到f(前100),不信你算一下前100个 ...

  3. Dijkstra_Liu博客100篇祭

    创建博客,有两年三个月了.今天,写了100篇随笔了,又正值我的15岁生日,还是值得纪念一下. 两年过去了,我从学习:队列.栈.模拟.背包慢慢地变成了:Tarjan.线段树.树剖. 我也从一个初一的天真 ...

  4. python3登录网页(163邮箱)实例

    # -*- coding: utf-8 -*- import urllibimport http.cookiejar as cookielibimport urllib.request as urll ...

  5. python开发_tkinter_小球完全弹性碰撞游戏_源码下载

    完成这个小球的完全弹性碰撞游戏灵感来自于: 下面是我花了一周下班时间所编写的一个小球完全弹性碰撞游戏: 游戏初始化状态: 最下面的游标和修改小球的移动速度 ====================== ...

  6. wikioi 1068 乌龟棋

    四维dp表示分别用了多少张卡后可以获得的最大分数 #include <cstdio> #include <cmath> #include <cstring> #in ...

  7. JavaScript和JSP的区别?

    名字: JS:JavaScript JSP:Java Server Pages 执行过程:JSP先翻译,翻译成Servlet执行 如: test.jsp 要变成 test_jsp.java 然后编译成 ...

  8. 读书笔记_Effective_C++_条款三十六:绝不重新定义继承而来的non-virtual函数

    这个条款的内容很简单,见下面的示例: class BaseClass { public: void NonVirtualFunction() { cout << "BaseCla ...

  9. SpringBoot读取配置properties配置文件

    见:http://www.cnblogs.com/VergiLyn/p/6286507.html

  10. IntelliJ IDEA代码分屏显示