LeetCode题解: LRU Cache 缓存设计

 

LeetCode题解: LRU Cache 缓存设计

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/leread/article/details/41841965

设计并实现最近最久未使用(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。

复制代码
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的OJ不支持这样实现,将上面的代码修改后提交,提示 Comoile Error .

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

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

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

复制代码
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));
//        
//    }

}
复制代码

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

复制代码
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]
复制代码

 

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

 

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/chou_qi/article/details/84718012
直接贴代码

类: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)

引子:

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

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

LRU缓存:

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

实现:

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

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

 

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

 

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

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
    本文链接: https://blog.csdn.net/chengdezhi2011/article/details/76762623

     

     

     

    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 链表操作与缓存处理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/chengdezhi2011/article/details/76762623

 

 

 

  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.  

转载于:https://www.cnblogs.com/think90/p/11443184.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值