LeetCode题解: LRU Cache 缓存设计

LeetCode题解: LRU Cache 缓存设计

2014年12月10日 08:54:16 邴越 阅读数 1101更多
分类专栏: LeetCode
 
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。

设计并实现最近最久未使用(Least Recently Used)缓存。

链接:https://oj.leetcode.com/problems/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.

设计并实现最近最久未使用的缓存数据结构,支持 get 和 set 操作.

get()-如果 key 存在,返回对应的 value 值,否则返回 -1.

set()-插入 key 对应的 value 到缓存中,如果缓存已满,将最近最久未使用的元素从缓存中移除。

要实现这个设计,我们先回顾一下大学课堂上的知识。
LRU,即最近最少使用,是操作系统内存管理的一种页面置换算法,
常见的页面置换算法,最佳置换算法(OPT,理想置换算法),先进先出置换算法(FIFO),
最近最久未使用算法(LRU),最少使用算法。

其中,最佳置换算法是一种理想情况下的页面置换算法,实际上不可能实现。该算法的基本思想是发生缺页时,有些页面在内存中,其中有一页将很快被访问(也包含紧接着的下一条指令的那页),而其他页面则可能要到10、100或者1000条指令后才会被访问,每个页面都可以用在该页面首次被访问前所要执行的指令数进行标记。最佳页面置换算法规定标记最大的页应该被置换。但当缺页发生时,操作系统无法知道各个页面下一次是在什么时候被访问。这个算法无法实现,但可以用于对可实现算法的性能进行衡量。

另外两种主要算法,LFU算法-实现缓存,FIFO算法-实现缓存,可以查看这里

LRU的实现方法有很多,传统的LRU实现方法:

1.计数器。最简单的情况是使每个页表项对应一个使用时间字段,并给CPU增加一个逻辑时钟或计数器。每次存储访问,该时钟都加1。每当访问一个页面时,时钟寄存器的内容就被复制到相应页表项的使用时间字段中。这样我们就可以始终保留着每个页面最后访问的“时间”。在置换页面时,选择该时间值最小的页面。
2.栈。用一个栈保留页号。每当访问一个页面时,就把它从栈中取出放在栈顶上。这样一来,栈顶总是放有目前使用最多的页,而栈底放着目前最少使用的页。由于要从栈的中间移走一项,所以要用具有头尾指针的双向链连起来。

Java语言可以利用 LinkedHashMap, LinkedHashMap 是有序的哈希表,可以保存记录的插入顺序,并且按使用顺序排列。
重写其中的removeEldestEntry(Map.Entry)方法,就可以实现LRU算法。

我看了一下,在Mysql Jdbc Util和Apache的很多Jar包中,都是使用LinkedHashMap实现LRUCache。
下面的代码来自mysql-connector-java-5.1.18-bin.jar。

LeetCode题解: LRU Cache 缓存设计
package com.mysql.jdbc.util;

import java.util.LinkedHashMap;
import java.util.Map; public class LRUCache extends LinkedHashMap
{ public LRUCache(int maxSize)
{
super(maxSize, 0.75F, true);
maxElements = maxSize;
} protected boolean removeEldestEntry(java.util.Map.Entry eldest)
{
return size() > maxElements;
} private static final long serialVersionUID = 1L;
protected int maxElements;
}
LeetCode题解: LRU Cache 缓存设计

不过LeetCode的OJ不支持这样实现,将上面的代码修改后提交,提示 Comoile Error .

LeetCode题解: LRU Cache 缓存设计

JDK中,LinkedHashMap是通过继承HashMap,维护一个双链表实现,
当某个Cache位置被命中,通过调整链表的指向将该位置调整到头位置,新加入的内容直接放在链表头,在多次进行Cache操作后,最近使用的Cache就会向链表头部移动,链表尾部就是命中次数最少,最久未使用的Cache。空间充满时,移除尾部的数据就可以了。

题目有几点需要注意,一个是Key不存在的情况,一个是缓存设计要求Key唯一。

下面使用双向链表(双链表)实现LRU Cache,以下代码提交AC。

LeetCode题解: LRU Cache 缓存设计
import java.util.HashMap;
/**
* 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.
* 近期最少使用算法 设计缓存
*/
public class LRUCache { private int cacheSize;//缓存容量
private int currentSize;//当前容量
private HashMap<Object, CacheNode> nodes;//缓存容器
private CacheNode head;//链表头
private CacheNode last;//链表尾 class CacheNode{
CacheNode prev;//前一节点
CacheNode next;//后一节点
int value;//值
int key;//键
CacheNode() {
}
} //初始化缓存
public LRUCache(int capacity) {
currentSize=0;
cacheSize=capacity;
nodes=new HashMap<Object, CacheNode>(capacity);
} public Integer get(int key) {
CacheNode node = nodes.get(key);
if (node != null) {
move(node);
return node.value;
} else {
return -1;//error code
} } public void set(int key, int value) {
CacheNode node = nodes.get(key);
//重复Key
if(node!=null){
node.value=value;
move(node);
nodes.put(key, node);
}else
{//key未重复,正常流程
node =new CacheNode();
if(currentSize>=cacheSize){
if (last != null){//缓存已满,进行淘汰
nodes.remove(last.key);}
removeLast();//移除链表尾部并后移
}else{
currentSize++;
} node.key=key;
node.value=value;
move(node);
nodes.put(key, node);
}
} //移动链表节点至头部
private void move(CacheNode cacheNode){
if(cacheNode==head)
return;
//链接前后节点
if(cacheNode.prev!=null)
cacheNode.prev.next=cacheNode.next;
if(cacheNode.next!=null)
cacheNode.next.prev=cacheNode.prev;
//头尾节点
if (last == cacheNode)
last = cacheNode.prev;
if (head != null) {
cacheNode.next = head;
head.prev = cacheNode;
}
//移动后的链表
head = cacheNode;
cacheNode.prev = null;
//节点唯一的情况
if (last == null)
last = head;
} //移除指定缓存
public void remove(int key){
CacheNode cacheNode = nodes.get(key);
if (cacheNode != null) {
if (cacheNode.prev != null) {
cacheNode.prev.next = cacheNode.next;
}
if (cacheNode.next != null) {
cacheNode.next.prev = cacheNode.prev;
}
if (last == cacheNode)
last = cacheNode.prev;
if (head == cacheNode)
head = cacheNode.next;
} }
//删除尾部的结点,即去除最近最久未使用数据
private void removeLast(){
if(last!=null){
if(last.prev!=null){
last.prev.next=null;
}else{//空间大小为1的情况
head = null;
}
last = last.prev;
}
} public void clear() {
head = null;
last = null;
}
//测试用例
// public static void main(String[] args){
// LRUCache lCache=new LRUCache(2);
// lCache.set(2, 1);
// lCache.set(1, 1);
// lCache.set(2, 3);
// lCache.set(4, 1);
// System.out.println(lCache.get(1));
// System.out.println(lCache.get(2));
//
// } }
LeetCode题解: LRU Cache 缓存设计

下面是提交中遇到的几组测试用例:

LeetCode题解: LRU Cache 缓存设计
Input:    2,[get(2),set(2,6),get(1),set(1,5),set(1,2),get(1),get(2)]
Expected: [-1,-1,2,6]
Input: 2,[set(2,1),set(1,1),set(2,3),set(4,1),get(1),get(2)]
Expected: [-1,3]
Input: 1,[get(0)]
Expected: [-1]
LeetCode题解: LRU Cache 缓存设计

同步:http://www.cnblogs.com/binyue/

LinkedHashMap 最远未被使用丢弃缓存算法Least Recently used

2015年05月12日 21:44:41 蔡召华 阅读数 61更多
分类专栏: 算法
 
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
直接贴代码

类:Test 
类: LeastRecentlyUsedLinkedHashMap<K,V>

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Test {
public static void main(String[] args) {
/**
* LinkedHashMap 实现了Least Recently used 最远未被使用丢弃缓存算法
* :在固定大小的LinkedHashMap中如果容量大于了 size() 将丢弃最远时间未被使用的key value 是一种缓存算法
*/

LeastRecentlyUsedLinkedHashMap<String, String> lruMap = new 
LeastRecentlyUsedLinkedHashMap<String, String>(5);
lruMap.put("1", "a");
lruMap.put("2", "ab");
lruMap.put("3", "abc");
lruMap.put("4", "abcd");
lruMap.put("5", "abcde");
lruMap.put("6", "abcdef");
lruMap.put("7", "abcdefg");

printMapContent(lruMap);

System.out.println("\n");
lruMap.get("3");
printMapContent(lruMap);

System.out.println("\n");
lruMap.put("8", "xxxxxx");
printMapContent(lruMap);

}

/**
* map循环
* @param lruMap
*/
public static void printMapContent(LeastRecentlyUsedLinkedHashMap lruMap){

Set<Map.Entry<String,String>> entrySet = lruMap.entrySet();

Iterator iter = entrySet.iterator();

Map.Entry<String,String> entry = null;

while(iter.hasNext()){
entry = (Entry<String, String>) iter.next();
System.out.println("key: " + entry.getKey()+" value: " +entry.getValue());
}
}
}

LRU算法实现类:

public class LeastRecentlyUsedLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

/**

*/
private static final long serialVersionUID = 1L;

/*指定map规定缓存容器长度*/
private int capacity;

LeastRecentlyUsedLinkedHashMap(int capacity){
super(capacity,0.75f,true);
this.capacity = capacity;
}

protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size()> capacity;
}

}

 

LRU缓存介绍与实现 (Java)

2013年12月19日 20:35:14 william_yao 阅读数 774更多
分类专栏: Java技术
 

引子:

我们平时总会有一个电话本记录所有朋友的电话,但是,如果有朋友经常联系,那些朋友的电话号码不用翻电话本我们也能记住,但是,如果长时间没有联系了,要再次联系那位朋友的时候,我们又不得不求助电话本,但是,通过电话本查找还是很费时间的。但是,我们大脑能够记住的东西是一定的,我们只能记住自己最熟悉的,而长时间不熟悉的自然就忘记了。

其实,计算机也用到了同样的一个概念,我们用缓存来存放以前读取的数据,而不是直接丢掉,这样,再次读取的时候,可以直接在缓存里面取,而不用再重新查找一遍,这样系统的反应能力会有很大提高。但是,当我们读取的个数特别大的时候,我们不可能把所有已经读取的数据都放在缓存里,毕竟内存大小是一定的,我们一般把最近常读取的放在缓存里(相当于我们把最近联系的朋友的姓名和电话放在大脑里一样)。现在,我们就来研究这样一种缓存机制。

LRU缓存:

LRU缓存利用了这样的一种思想。LRU是Least Recently Used 的缩写,翻译过来就是“最近最少使用”,也就是说,LRU缓存把最近最少使用的数据移除,让给最新读取的数据。而往往最常读取的,也是读取次数最多的,所以,利用LRU缓存,我们能够提高系统的performance.

实现:

要实现LRU缓存,我们首先要用到一个类 LinkedHashMap。 用这个类有两大好处:一是它本身已经实现了按照访问顺序的存储,也就是说,最近读取的会放在最前面,最最不常读取的会放在最后(当然,它也可以实现按照插入顺序存储)。第二,LinkedHashMap本身有一个方法用于判断是否需要移除最不常读取的数,但是,原始方法默认不需要移除(这是,LinkedHashMap相当于一个linkedlist),所以,我们需要override这样一个方法,使得当缓存里存放的数据个数超过规定个数后,就把最不常用的移除掉。LinkedHashMap的API写得很清楚,推荐大家可以先读一下。

要基于LinkedHashMap来实现LRU缓存,我们可以选择inheritance, 也可以选择 delegation, 我更喜欢delegation。基于delegation的实现已经有人写出来了,而且写得很漂亮,我就不班门弄斧了。代码如下:

  1. import java.util.LinkedHashMap;
  2. import java.util.Collection;
  3. import java.util.Map;
  4. import java.util.ArrayList;
  5. /**
  6. * An LRU cache, based on <code>LinkedHashMap</code>.
  7. *
  8. * <p>
  9. * This cache has a fixed maximum number of elements (<code>cacheSize</code>).
  10. * If the cache is full and another entry is added, the LRU (least recently used) entry is dropped.
  11. *
  12. * <p>
  13. * This class is thread-safe. All methods of this class are synchronized.
  14. *
  15. * <p>
  16. * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
  17. * Multi-licensed: EPL / LGPL / GPL / AL / BSD.
  18. */
  19. public class LRUCache<K,V> {
  20. private static final float   hashTableLoadFactor = 0.75f;
  21. private LinkedHashMap<K,V>   map;
  22. private int                  cacheSize;
  23. /**
  24. * Creates a new LRU cache.
  25. * @param cacheSize the maximum number of entries that will be kept in this cache.
  26. */
  27. public LRUCache (int cacheSize) {
  28. this.cacheSize = cacheSize;
  29. int hashTableCapacity = (int)Math.ceil(cacheSize / hashTableLoadFactor) + 1;
  30. map = new LinkedHashMap<K,V>(hashTableCapacity, hashTableLoadFactor, true) {
  31. // (an anonymous inner class)
  32. private static final long serialVersionUID = 1;
  33. @Override protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
  34. return size() > LRUCache.this.cacheSize; }}; }
  35. /**
  36. * Retrieves an entry from the cache.<br>
  37. * The retrieved entry becomes the MRU (most recently used) entry.
  38. * @param key the key whose associated value is to be returned.
  39. * @return    the value associated to this key, or null if no value with this key exists in the cache.
  40. */
  41. public synchronized V get (K key) {
  42. return map.get(key); }
  43. /**
  44. * Adds an entry to this cache.
  45. * The new entry becomes the MRU (most recently used) entry.
  46. * If an entry with the specified key already exists in the cache, it is replaced by the new entry.
  47. * If the cache is full, the LRU (least recently used) entry is removed from the cache.
  48. * @param key    the key with which the specified value is to be associated.
  49. * @param value  a value to be associated with the specified key.
  50. */
  51. public synchronized void put (K key, V value) {
  52. map.put (key, value); }
  53. /**
  54. * Clears the cache.
  55. */
  56. public synchronized void clear() {
  57. map.clear(); }
  58. /**
  59. * Returns the number of used entries in the cache.
  60. * @return the number of entries currently in the cache.
  61. */
  62. public synchronized int usedEntries() {
  63. return map.size(); }
  64. /**
  65. * Returns a <code>Collection</code> that contains a copy of all cache entries.
  66. * @return a <code>Collection</code> with a copy of the cache content.
  67. */
  68. public synchronized Collection<Map.Entry<K,V>> getAll() {
  69. return new ArrayList<Map.Entry<K,V>>(map.entrySet()); }
  70. } // end class LRUCache
  71. ------------------------------------------------------------------------------------------
  72. // Test routine for the LRUCache class.
  73. public static void main (String[] args) {
  74. LRUCache<String,String> c = new LRUCache<String, String>(3);
  75. c.put ("1", "one");                           // 1
  76. c.put ("2", "two");                           // 2 1
  77. c.put ("3", "three");                         // 3 2 1
  78. c.put ("4", "four");                          // 4 3 2
  79. if (c.get("2") == null) throw new Error();    // 2 4 3
  80. c.put ("5", "five");                          // 5 2 4
  81. c.put ("4", "second four");                   // 4 5 2
  82. // Verify cache content.
  83. if (c.usedEntries() != 3)              throw new Error();
  84. if (!c.get("4").equals("second four")) throw new Error();
  85. if (!c.get("5").equals("five"))        throw new Error();
  86. if (!c.get("2").equals("two"))         throw new Error();
  87. // List cache content.
  88. for (Map.Entry<String, String> e : c.getAll())
  89. System.out.println (e.getKey() + " : " + e.getValue()); }

代码出自:http://www.source-code.biz/snippets/java/6.htm

在博客 http://gogole.iteye.com/blog/692103 里,作者使用的是双链表 + hashtable 的方式实现的。如果在面试题里考到如何实现LRU,考官一般会要求使用双链表 + hashtable 的方式。 所以,我把原文的部分内容摘抄如下:

双链表 + hashtable实现原理:

将Cache的所有位置都用双连表连接起来,当一个位置被命中之后,就将通过调整链表的指向,将该位置调整到链表头的位置,新加入的Cache直接加到链表头中。这样,在多次进行Cache操作后,最近被命中的,就会被向链表头方向移动,而没有命中的,而想链表后面移动,链表尾则表示最近最少使用的Cache。当需要替换内容时候,链表的最后位置就是最少被命中的位置,我们只需要淘汰链表最后的部分即可。

  1. public class LRUCache {
  2. private int cacheSize;
  3. private Hashtable<Object, Entry> nodes;//缓存容器
  4. private int currentSize;
  5. private Entry first;//链表头
  6. private Entry last;//链表尾
  7. public LRUCache(int i) {
  8. currentSize = 0;
  9. cacheSize = i;
  10. nodes = new Hashtable<Object, Entry>(i);//缓存容器
  11. }
  12. /**
  13. * 获取缓存中对象,并把它放在最前面
  14. */
  15. public Entry get(Object key) {
  16. Entry node = nodes.get(key);
  17. if (node != null) {
  18. moveToHead(node);
  19. return node;
  20. } else {
  21. return null;
  22. }
  23. }
  24. /**
  25. * 添加 entry到hashtable, 并把entry
  26. */
  27. public void put(Object key, Object value) {
  28. //先查看hashtable是否存在该entry, 如果存在,则只更新其value
  29. Entry node = nodes.get(key);
  30. if (node == null) {
  31. //缓存容器是否已经超过大小.
  32. if (currentSize >= cacheSize) {
  33. nodes.remove(last.key);
  34. removeLast();
  35. } else {
  36. currentSize++;
  37. }
  38. node = new Entry();
  39. }
  40. node.value = value;
  41. //将最新使用的节点放到链表头,表示最新使用的.
  42. moveToHead(node);
  43. nodes.put(key, node);
  44. }
  45. /**
  46. * 将entry删除, 注意:删除操作只有在cache满了才会被执行
  47. */
  48. public void remove(Object key) {
  49. Entry node = nodes.get(key);
  50. //在链表中删除
  51. if (node != null) {
  52. if (node.prev != null) {
  53. node.prev.next = node.next;
  54. }
  55. if (node.next != null) {
  56. node.next.prev = node.prev;
  57. }
  58. if (last == node)
  59. last = node.prev;
  60. if (first == node)
  61. first = node.next;
  62. }
  63. //在hashtable中删除
  64. nodes.remove(key);
  65. }
  66. /**
  67. * 删除链表尾部节点,即使用最后 使用的entry
  68. */
  69. private void removeLast() {
  70. //链表尾不为空,则将链表尾指向null. 删除连表尾(删除最少使用的缓存对象)
  71. if (last != null) {
  72. if (last.prev != null)
  73. last.prev.next = null;
  74. else
  75. first = null;
  76. last = last.prev;
  77. }
  78. }
  79. /**
  80. * 移动到链表头,表示这个节点是最新使用过的
  81. */
  82. private void moveToHead(Entry node) {
  83. if (node == first)
  84. return;
  85. if (node.prev != null)
  86. node.prev.next = node.next;
  87. if (node.next != null)
  88. node.next.prev = node.prev;
  89. if (last == node)
  90. last = node.prev;
  91. if (first != null) {
  92. node.next = first;
  93. first.prev = node;
  94. }
  95. first = node;
  96. node.prev = null;
  97. if (last == null)
  98. last = first;
  99. }
  100. /*
  101. * 清空缓存
  102. */
  103. public void clear() {
  104. first = null;
  105. last = null;
  106. currentSize = 0;
  107. }
  108. }
  109. class Entry {
  110. Entry prev;//前一节点
  111. Entry next;//后一节点
  112. Object value;//值
  113. Object key;//键
  114. }
  115. leetcode 146. LRU Cache 链表操作与缓存处理

    2017年08月06日 12:11:26 Hackerzer 阅读数 568更多
    分类专栏: 算法
     
    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
    1.  
      public class LRUCache {
    2.  
      class DlinkedNote{
    3.  
      int key;
    4.  
      int value;
    5.  
      DlinkedNote pre;
    6.  
      DlinkedNote post;
    7.  
      DlinkedNote(){}
    8.  
      DlinkedNote(int key, int value){
    9.  
      this.key = key;
    10.  
      this.value = value;
    11.  
      }
    12.  
      }
    13.  
       
    14.  
      HashMap<Integer, DlinkedNote> cache = new HashMap<Integer, DlinkedNote>();
    15.  
      int capacity;
    16.  
      DlinkedNote head;
    17.  
      DlinkedNote tail;
    18.  
       
    19.  
       
    20.  
      public DlinkedNote poptail(){
    21.  
      DlinkedNote res = tail.pre;
    22.  
      removenode(res);
    23.  
      return res;
    24.  
      }
    25.  
       
    26.  
      public void movetohead(DlinkedNote node){
    27.  
      removenode(node);
    28.  
      addnode(node);
    29.  
      }
    30.  
       
    31.  
      public void removenode(DlinkedNote node){
    32.  
      DlinkedNote pre = node.pre;
    33.  
      DlinkedNote post = node.post;
    34.  
      pre.post = post;
    35.  
      post.pre = pre;
    36.  
      }
    37.  
       
    38.  
      /** always add at the head of link*/
    39.  
      public void addnode(DlinkedNote node){
    40.  
      DlinkedNote cur_first = this.head.post;
    41.  
      cur_first.pre = node;
    42.  
      node.post = cur_first;
    43.  
      node.pre = this.head;
    44.  
      this.head.post = node;
    45.  
      }
    46.  
       
    47.  
      public LRUCache(int capacity) {
    48.  
      DlinkedNote head = new DlinkedNote();
    49.  
      DlinkedNote tail = new DlinkedNote();
    50.  
      head.post = tail;
    51.  
      tail.pre = head;
    52.  
      this.head = head;
    53.  
      this.tail = tail;
    54.  
      this.capacity = capacity;
    55.  
      // this.count = 0;
    56.  
      }
    57.  
       
    58.  
      public int get(int key) {
    59.  
      DlinkedNote res = cache.get(key);
    60.  
      if(res==null){
    61.  
      return -1;
    62.  
      }
    63.  
      movetohead(res);
    64.  
      return res.value;
    65.  
      }
    66.  
       
    67.  
      public void put(int key, int value) {
    68.  
      DlinkedNote node = cache.get(key);
    69.  
      int count = cache.size();
    70.  
      if(node==null){
    71.  
      DlinkedNote new_node = new DlinkedNote(key, value);
    72.  
      this.cache.put(key, new_node);
    73.  
      addnode(new_node);
    74.  
      count++;
    75.  
      // while(count>this.capacity)
    76.  
      if(count>this.capacity){
    77.  
      DlinkedNote last = this.poptail();
    78.  
      cache.remove(last.key);
    79.  
      }
    80.  
      }else{
    81.  
      if(node.value!=value){
    82.  
      node.value = value;
    83.  
      }
    84.  
      movetohead(node);
    85.  
      }
    86.  
      }
    87.  

leetcode 146. LRU Cache 链表操作与缓存处理

2017年08月06日 12:11:26 Hackerzer 阅读数 568更多
分类专栏: 算法
 
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
  1.  
    public class LRUCache {
  2.  
    class DlinkedNote{
  3.  
    int key;
  4.  
    int value;
  5.  
    DlinkedNote pre;
  6.  
    DlinkedNote post;
  7.  
    DlinkedNote(){}
  8.  
    DlinkedNote(int key, int value){
  9.  
    this.key = key;
  10.  
    this.value = value;
  11.  
    }
  12.  
    }
  13.  
     
  14.  
    HashMap<Integer, DlinkedNote> cache = new HashMap<Integer, DlinkedNote>();
  15.  
    int capacity;
  16.  
    DlinkedNote head;
  17.  
    DlinkedNote tail;
  18.  
     
  19.  
     
  20.  
    public DlinkedNote poptail(){
  21.  
    DlinkedNote res = tail.pre;
  22.  
    removenode(res);
  23.  
    return res;
  24.  
    }
  25.  
     
  26.  
    public void movetohead(DlinkedNote node){
  27.  
    removenode(node);
  28.  
    addnode(node);
  29.  
    }
  30.  
     
  31.  
    public void removenode(DlinkedNote node){
  32.  
    DlinkedNote pre = node.pre;
  33.  
    DlinkedNote post = node.post;
  34.  
    pre.post = post;
  35.  
    post.pre = pre;
  36.  
    }
  37.  
     
  38.  
    /** always add at the head of link*/
  39.  
    public void addnode(DlinkedNote node){
  40.  
    DlinkedNote cur_first = this.head.post;
  41.  
    cur_first.pre = node;
  42.  
    node.post = cur_first;
  43.  
    node.pre = this.head;
  44.  
    this.head.post = node;
  45.  
    }
  46.  
     
  47.  
    public LRUCache(int capacity) {
  48.  
    DlinkedNote head = new DlinkedNote();
  49.  
    DlinkedNote tail = new DlinkedNote();
  50.  
    head.post = tail;
  51.  
    tail.pre = head;
  52.  
    this.head = head;
  53.  
    this.tail = tail;
  54.  
    this.capacity = capacity;
  55.  
    // this.count = 0;
  56.  
    }
  57.  
     
  58.  
    public int get(int key) {
  59.  
    DlinkedNote res = cache.get(key);
  60.  
    if(res==null){
  61.  
    return -1;
  62.  
    }
  63.  
    movetohead(res);
  64.  
    return res.value;
  65.  
    }
  66.  
     
  67.  
    public void put(int key, int value) {
  68.  
    DlinkedNote node = cache.get(key);
  69.  
    int count = cache.size();
  70.  
    if(node==null){
  71.  
    DlinkedNote new_node = new DlinkedNote(key, value);
  72.  
    this.cache.put(key, new_node);
  73.  
    addnode(new_node);
  74.  
    count++;
  75.  
    // while(count>this.capacity)
  76.  
    if(count>this.capacity){
  77.  
    DlinkedNote last = this.poptail();
  78.  
    cache.remove(last.key);
  79.  
    }
  80.  
    }else{
  81.  
    if(node.value!=value){
  82.  
    node.value = value;
  83.  
    }
  84.  
    movetohead(node);
  85.  
    }
  86.  
    }
  87.  
上一篇:Oracle12c中PL/SQL(DBMS_SQL)新特性之隐式语句结果(DBMS_SQL.RETURN_RESULT and DBMS_SQL.GET_NEXT_RESULT)


下一篇:HDU 2767 Proving Equivalences(强连通 Tarjan+缩点)