LFU五种实现方式,从简单到复杂

开发 前端
虽然,力扣要求是用时间复杂度 O(1) 来解,但是其它方式我感觉也有必要了解,毕竟是一个由浅到深的过程,自己实现一遍总归是好的。因此,我就把五种求解方式,从简单到复杂,都讲一遍。

[[329667]]

前言

最近刷力扣题,对于我这种 0 基础来说,真的是脑壳疼啊。这个月我估计都是中等和困难题,没有简单题了。

幸好,力扣上有各种大牛给写题解。看着他们行云流水的代码,真的是羡慕不已。让我印象最深刻的就是人称 “甜姨” 的知心姐姐,还有名叫威哥的大哥。几乎每天他们的题解我都是必看的。

甜姨的题解,虽然姿势很帅,但是对于我这种新手来说,感觉不是太友好,因为思路写的太少,不是很详细。所以,每次我看不明白的时候,都得反复看好几遍,才能想明白她代码中的思路。

上个周末的一道题是,让实现一个 LFU 缓存算法。经过我几个小时的研究(其实,应该有8个小时以上了,没得办法啊,菜就得多勤奋咯),终于把甜姨的思路整明白了。为了便于以后自己复习,就把整个思路记下来了,并配上图示和大量代码注释,我相信对于跟我一样的新手来说,是非常友好的。

经过甜姨同意,参考来源我也会贴出来:https://leetcode-cn.com/problems/lfu-cache/solution/java-13ms-shuang-100-shuang-xiang-lian-biao-duo-ji/

虽然,力扣要求是用时间复杂度 O(1) 来解,但是其它方式我感觉也有必要了解,毕竟是一个由浅到深的过程,自己实现一遍总归是好的。因此,我就把五种求解方式,从简单到复杂,都讲一遍。

LFU实现

力扣原题描述如下:

  1. 请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。它应该支持以下操作:get 和 put。 
  2.  
  3. get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。 
  4. put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近 最少使用的键。 
  5. 「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。 
  6.  
  7. 示例: 
  8.  
  9. LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ ); 
  10.  
  11. cache.put(1, 1); 
  12. cache.put(2, 2); 
  13. cache.get(1);       // 返回 1 
  14. cache.put(3, 3);    // 去除 key 2 
  15. cache.get(2);       // 返回 -1 (未找到key 2) 
  16. cache.get(3);       // 返回 3 
  17. cache.put(4, 4);    // 去除 key 1 
  18. cache.get(1);       // 返回 -1 (未找到 key 1) 
  19. cache.get(3);       // 返回 3 
  20. cache.get(4);       // 返回 4 
  21.  
  22. 来源:力扣(LeetCode) 
  23. 链接:https://leetcode-cn.com/problems/lfu-cache 

就是要求我们设计一个 LFU 算法,根据访问次数(访问频次)大小来判断应该删除哪个元素,get和put操作都会增加访问频次。当访问频次相等时,就判断哪个元素是最久未使用过的,把它删除。

因此,这道题需要考虑两个方面,一个是访问频次,一个是访问时间的先后顺序。

方案一:使用优先队列思路:

我们可以使用JDK提供的优先队列 PriorityQueue 来实现 。因为优先队列内部维护了一个二叉堆,即可以保证每次 poll 元素的时候,都可以根据我们的要求,取出当前所有元素的最大值或是最小值。只需要我们的实体类实现 Comparable 接口就可以了。

因此,我们需要定义一个 Node 来保存当前元素的访问频次 freq,全局的自增的 index,用于比较大小。然后定义一个 Map

当 cache 容量不足时,根据访问频次 freq 的大小来删除最小的 freq 。若相等,则删除 index 最小的,因为index是自增的,越大说明越是最近访问过的,越小说明越是很长时间没访问过的元素。

因本质是用二叉堆实现,故时间复杂度为O(logn)。

  1. public class LFUCache4 { 
  2.  
  3.     public static void main(String[] args) { 
  4.         LFUCache4 cache = new LFUCache4(2); 
  5.         cache.put(1, 1); 
  6.         cache.put(2, 2); 
  7.         // 返回 1 
  8.         System.out.println(cache.get(1)); 
  9.         cache.put(3, 3);    // 去除 key 2 
  10.         // 返回 -1 (未找到key 2) 
  11.         System.out.println(cache.get(2)); 
  12.         // 返回 3 
  13.         System.out.println(cache.get(3)); 
  14.         cache.put(4, 4);    // 去除 key 1 
  15.         // 返回 -1 (未找到 key 1) 
  16.         System.out.println(cache.get(1)); 
  17.         // 返回 3 
  18.         System.out.println(cache.get(3)); 
  19.         // 返回 4 
  20.         System.out.println(cache.get(4)); 
  21.     } 
  22.  
  23.     //缓存了所有元素的node 
  24.     Map<Integer,Node> cache; 
  25.     //优先队列 
  26.     Queue<Node> queue; 
  27.     //缓存cache 的容量 
  28.     int capacity; 
  29.     //当前缓存的元素个数 
  30.     int size
  31.     //全局自增 
  32.     int index = 0; 
  33.  
  34.     //初始化 
  35.     public LFUCache4(int capacity){ 
  36.         this.capacity = capacity; 
  37.         if(capacity > 0){ 
  38.             queue = new PriorityQueue<>(capacity); 
  39.         } 
  40.         cache = new HashMap<>(); 
  41.     } 
  42.  
  43.     public int get(int key){ 
  44.         Node node = cache.get(key); 
  45.         // node不存在,则返回 -1 
  46.         if(node == nullreturn -1; 
  47.         //每访问一次,频次和全局index都自增 1 
  48.         node.freq++; 
  49.         node.index = index++; 
  50.         // 每次都重新remove,再offer是为了让优先队列能够对当前Node重排序 
  51.         //不然的话,比较的 freq 和 index 就是不准确的 
  52.         queue.remove(node); 
  53.         queue.offer(node); 
  54.         return node.value; 
  55.     } 
  56.  
  57.     public void put(int keyint value){ 
  58.         //容量0,则直接返回 
  59.         if(capacity == 0) return
  60.         Node node = cache.get(key); 
  61.         //如果node存在,则更新它的value值 
  62.         if(node != null){ 
  63.             node.value = value; 
  64.             node.freq++; 
  65.             node.index = index++; 
  66.             queue.remove(node); 
  67.             queue.offer(node); 
  68.         }else { 
  69.             //如果cache满了,则从优先队列中取出一个元素,这个元素一定是频次最小,最久未访问过的元素 
  70.             if(size == capacity){ 
  71.                 cache.remove(queue.poll().key); 
  72.                 //取出元素后,size减 1 
  73.                 size--; 
  74.             } 
  75.             //否则,说明可以添加元素,于是创建一个新的node,添加到优先队列中 
  76.             Node newNode = new Node(key, value, index++); 
  77.             queue.offer(newNode); 
  78.             cache.put(key,newNode); 
  79.             //同时,size加 1 
  80.             size++; 
  81.         } 
  82.     } 
  83.  
  84.  
  85.     //必须实现 Comparable 接口才可用于排序 
  86.     private class Node implements Comparable<Node>{ 
  87.         int key
  88.         int value; 
  89.         int freq = 1; 
  90.         int index
  91.  
  92.         public Node(){ 
  93.  
  94.         } 
  95.  
  96.         public Node(int keyint value, int index){ 
  97.             this.key = key
  98.             this.value = value; 
  99.             this.index = index
  100.         } 
  101.  
  102.         @Override 
  103.         public int compareTo(Node o) { 
  104.             //优先比较频次 freq,频次相同再比较index 
  105.             int minus = this.freq - o.freq; 
  106.             return minus == 0? this.index - o.index : minus; 
  107.         } 
  108.     } 

方案二:使用一条双向链表

思路:

只用一条双向链表,来维护频次和时间先后顺序。那么,可以这样想。把频次 freq 小的放前面,频次大的放后面。如果频次相等,就从当前节点往后遍历,直到找到第一个频次比它大的元素,并插入到它前面。(当然,如果遍历到了tail,则插入到tail前面)这样可以保证同频次的元素,最近访问的总是在最后边。

因此,总的来说,最低频次,并且最久未访问的元素肯定就是链表中最前面的那一个了。这样的话,当 cache容量满的时候,直接把头结点删除掉就可以了。但是,我们这里为了方便链表的插入和删除操作,用了两个哨兵节点,来表示头节点 head和尾结点tail。因此,删除头结点就相当于删除 head.next。

PS:哨兵节点只是为了占位,实际并不存储有效数据,只是为了链表插入和删除时,不用再判断当前节点的位置。不然的话,若当前节点占据了头结点或尾结点的位置,还需要重新赋值头尾节点元素,较麻烦。

为了便于理解新节点如何插入到链表中合适的位置,作图如下:

 

代码如下:

  1. public class LFUCache { 
  2.  
  3.     public static void main(String[] args) { 
  4.         LFUCache cache = new LFUCache(2); 
  5.         cache.put(1, 1); 
  6.         cache.put(2, 2); 
  7.         // 返回 1 
  8.         System.out.println(cache.get(1)); 
  9.         cache.put(3, 3);    // 去除 key 2 
  10.         // 返回 -1 (未找到key 2) 
  11.         System.out.println(cache.get(2)); 
  12.         // 返回 3 
  13.         System.out.println(cache.get(3)); 
  14.         cache.put(4, 4);    // 去除 key 1 
  15.         // 返回 -1 (未找到 key 1) 
  16.         System.out.println(cache.get(1)); 
  17.         // 返回 3 
  18.         System.out.println(cache.get(3)); 
  19.         // 返回 4 
  20.         System.out.println(cache.get(4)); 
  21.  
  22.     } 
  23.  
  24.     private Map<Integer,Node> cache; 
  25.     private Node head; 
  26.     private Node tail; 
  27.     private int capacity; 
  28.     private int size
  29.  
  30.     public LFUCache(int capacity) { 
  31.         this.capacity = capacity; 
  32.         this.cache = new HashMap<>(); 
  33.         /** 
  34.          * 初始化头结点和尾结点,并作为哨兵节点 
  35.          */ 
  36.         head = new Node(); 
  37.         tail = new Node(); 
  38.         head.next = tail; 
  39.         tail.pre = head; 
  40.     } 
  41.  
  42.     public int get(int key) { 
  43.         Node node = cache.get(key); 
  44.         if(node == nullreturn -1; 
  45.         node.freq++; 
  46.         moveToPostion(node); 
  47.         return node.value; 
  48.     } 
  49.  
  50.     public void put(int keyint value) { 
  51.         if(capacity == 0) return
  52.         Node node = cache.get(key); 
  53.         if(node != null){ 
  54.             node.value = value; 
  55.             node.freq++; 
  56.             moveToPostion(node); 
  57.         }else
  58.             //如果元素满了 
  59.             if(size == capacity){ 
  60.                 //直接移除最前面的元素,因为这个节点就是频次最小,且最久未访问的节点 
  61.                 cache.remove(head.next.key); 
  62.                 removeNode(head.next); 
  63.                 size--; 
  64.             } 
  65.             Node newNode = new Node(key, value); 
  66.             //把新元素添加进来 
  67.             addNode(newNode); 
  68.             cache.put(key,newNode); 
  69.             size++; 
  70.         } 
  71.     } 
  72.  
  73.     //只要当前 node 的频次大于等于它后边的节点,就一直向后找, 
  74.     // 直到找到第一个比当前node频次大的节点,或者tail节点,然后插入到它前面 
  75.     private void moveToPostion(Node node){ 
  76.         Node nextNode = node.next
  77.         //先把当前元素删除 
  78.         removeNode(node); 
  79.         //遍历到符合要求的节点 
  80.         while (node.freq >= nextNode.freq && nextNode != tail){ 
  81.             nextNode = nextNode.next
  82.         } 
  83.         //把当前元素插入到nextNode前面 
  84.         node.pre = nextNode.pre; 
  85.         node.next = nextNode; 
  86.         nextNode.pre.next = node; 
  87.         nextNode.pre = node; 
  88.  
  89.     } 
  90.  
  91.     //添加元素(头插法),并移动到合适的位置 
  92.     private void addNode(Node node){ 
  93.         node.pre = head; 
  94.         node.next = head.next
  95.         head.next.pre = node; 
  96.         head.next = node; 
  97.         moveToPostion(node); 
  98.     } 
  99.  
  100.     //移除元素 
  101.     private void removeNode(Node node){ 
  102.         node.pre.next = node.next
  103.         node.next.pre = node.pre; 
  104.     } 
  105.  
  106.     class Node { 
  107.         int key
  108.         int value; 
  109.         int freq = 1; 
  110.         //当前节点的前一个节点 
  111.         Node pre; 
  112.         //当前节点的后一个节点 
  113.         Node next
  114.  
  115.         public Node(){ 
  116.  
  117.         } 
  118.  
  119.         public Node(int key ,int value){ 
  120.             this.key = key
  121.             this.value = value; 
  122.         } 
  123.     } 

可以看到不管是插入元素还是删除元素时,都不需要额外的判断,这就是设置哨兵节点的好处。

由于每次访问元素的时候,都需要按一定的规则把元素放置到合适的位置,因此,元素需要从前往后一直遍历。所以,时间复杂度 O(n)。

方案三:用 LinkedHashSet维护频次链表

思路:

我们不再使用一条链表,同时维护频次和访问时间了。此处,换为用 map 键值对来维护,用频次作为键,用当前频次对应的一条具有先后访问顺序的链表来作为值。它的结构如下:

  1. Map<Integer, LinkedHashSet<Node>> freqMap 

 

由于LinkedHashSet 的 iterator迭代方法是按插入顺序的,因此迭代到的第一个元素肯定是当前频次下,最久未访问的元素。这样的话,当缓存 cache满的时候,直接删除迭代到的第一个元素就可以了。

另外 freqMap,也需要在每次访问元素的时候,重新维护关系。从当前元素的频次对应的双向链表中移除当前元素,并加入到高频次的链表中。

  1. public class LFUCache1 { 
  2.  
  3.     public static void main(String[] args) { 
  4.         LFUCache1 cache = new LFUCache1(2); 
  5.         cache.put(1, 1); 
  6.         cache.put(2, 2); 
  7.         // 返回 1 
  8.         System.out.println(cache.get(1)); 
  9.         cache.put(3, 3);    // 去除 key 2 
  10.         // 返回 -1 (未找到key 2) 
  11.         System.out.println(cache.get(2)); 
  12.         // 返回 3 
  13.         System.out.println(cache.get(3)); 
  14.         cache.put(4, 4);    // 去除 key 1 
  15.         // 返回 -1 (未找到 key 1) 
  16.         System.out.println(cache.get(1)); 
  17.         // 返回 3 
  18.         System.out.println(cache.get(3)); 
  19.         // 返回 4 
  20.         System.out.println(cache.get(4)); 
  21.     } 
  22.  
  23.     //缓存 cache 
  24.     private Map<Integer,Node> cache; 
  25.     //存储频次和对应双向链表关系的map 
  26.     private Map<Integer, LinkedHashSet<Node>> freqMap; 
  27.     private int capacity; 
  28.     private int size
  29.     //存储最小频次值 
  30.     private int min
  31.  
  32.     public LFUCache1(int capacity) { 
  33.         this.capacity = capacity; 
  34.         cache = new HashMap<>(); 
  35.         freqMap = new HashMap<>(); 
  36.     } 
  37.  
  38.     public int get(int key) { 
  39.         Node node = cache.get(key); 
  40.         if(node == nullreturn -1; 
  41.         //若找到当前元素,则频次加1 
  42.         freqInc(node); 
  43.         return node.value; 
  44.     } 
  45.  
  46.     public void put(int keyint value) { 
  47.         if(capacity == 0) return
  48.         Node node = cache.get(key); 
  49.         if(node != null){ 
  50.             node.value = value; 
  51.             freqInc(node); 
  52.         }else
  53.             if(size == capacity){ 
  54.                 Node deadNode = removeNode(); 
  55.                 cache.remove(deadNode.key); 
  56.                 size --; 
  57.             } 
  58.             Node newNode = new Node(key,value); 
  59.             cache.put(key,newNode); 
  60.             addNode(newNode); 
  61.             size++; 
  62.         } 
  63.     } 
  64.  
  65.     //处理频次map 
  66.     private void freqInc(Node node){ 
  67.         //从原来的频次对应的链表中删除当前node 
  68.         LinkedHashSet<Node> set = freqMap.get(node.freq); 
  69.         if(set != null
  70.             set.remove(node); 
  71.         //如果当前频次是最小频次,并且移除元素后,链表为空,则更新min值 
  72.         if(node.freq == min && set.size() == 0){ 
  73.             min = node.freq + 1; 
  74.         } 
  75.         //添加到新的频次对应的链表 
  76.         node.freq ++; 
  77.         LinkedHashSet<Node> newSet = freqMap.get(node.freq); 
  78.         //如果高频次链表还未存在,则初始化一条 
  79.         if(newSet == null){ 
  80.             newSet = new LinkedHashSet<Node>(); 
  81.             freqMap.put(node.freq,newSet); 
  82.         } 
  83.         newSet.add(node); 
  84.     } 
  85.  
  86.     //添加元素,更新频次 
  87.     private void addNode(Node node){ 
  88.         //添加新元素,肯定是需要加入到频次为1的链表中的 
  89.         LinkedHashSet<Node> set = freqMap.get(1); 
  90.         if(set == null){ 
  91.             set = new LinkedHashSet<>(); 
  92.             freqMap.put(1,set); 
  93.         } 
  94.         set.add(node); 
  95.         //更新最小频次为1 
  96.         min = 1; 
  97.     } 
  98.  
  99.     //删除频次最小,最久未访问的元素 
  100.     private Node removeNode(){ 
  101.         //找到最小频次对应的 LinkedHashSet 
  102.         LinkedHashSet<Node> set = freqMap.get(min); 
  103.         //迭代到的第一个元素就是最久未访问的元素,移除之 
  104.         Node node = set.iterator().next(); 
  105.         set.remove(node); 
  106.         //如果当前node的频次等于最小频次,并且移除元素之后,set为空,则 min 加1 
  107.         if(node.freq == min && set.size() == 0){ 
  108.             min ++; 
  109.         } 
  110.         return node; 
  111.     } 
  112.  
  113.     private class Node { 
  114.         int key
  115.         int value; 
  116.         int freq = 1; 
  117.  
  118.         public Node(int keyint value){ 
  119.             this.key = key
  120.             this.value = value; 
  121.         } 
  122.  
  123.         public Node(){ 
  124.  
  125.         } 
  126.     } 

方案四:手动实现一个频次链表

思路:

由于方案三用的是JDK自带的 LinkedHashSet ,其是实现了哈希表和双向链表的一个类,因此为了减少哈希相关的计算,提高效率,我们自己实现一条双向链表来替代它。

那么,这条双向链表,就需要维护当前频次下的所有元素的先后访问顺序。我们采用头插法,把新加入的元素添加到链表头部,这样的话,最久未访问的元素就在链表的尾部。

同样的,我们也用两个哨兵节点来代表头尾节点,以方便链表的操作。

 

代码如下:

  1. public class LFUCache2 { 
  2.  
  3.     public static void main(String[] args) { 
  4.         LFUCache2 cache = new LFUCache2(2); 
  5.         cache.put(1, 1); 
  6.         cache.put(2, 2); 
  7.         // 返回 1 
  8.         System.out.println(cache.get(1)); 
  9.         cache.put(3, 3);    // 去除 key 2 
  10.         // 返回 -1 (未找到key 2) 
  11.         System.out.println(cache.get(2)); 
  12.         // 返回 3 
  13.         System.out.println(cache.get(3)); 
  14.         cache.put(4, 4);    // 去除 key 1 
  15.         // 返回 -1 (未找到 key 1) 
  16.         System.out.println(cache.get(1)); 
  17.         // 返回 3 
  18.         System.out.println(cache.get(3)); 
  19.         // 返回 4 
  20.         System.out.println(cache.get(4)); 
  21.     } 
  22.  
  23.     private Map<Integer,Node> cache; 
  24.     private Map<Integer,DoubleLinkedList> freqMap; 
  25.     private int capacity; 
  26.     private int size
  27.     private int min
  28.  
  29.     public LFUCache2(int capacity){ 
  30.         this.capacity = capacity; 
  31.         cache = new HashMap<>(); 
  32.         freqMap = new HashMap<>(); 
  33.     } 
  34.  
  35.     public int get(int key){ 
  36.         Node node = cache.get(key); 
  37.         if(node == nullreturn -1; 
  38.         freqInc(node); 
  39.         return node.value; 
  40.     } 
  41.  
  42.     public void put(int keyint value){ 
  43.         if(capacity == 0) return
  44.         Node node = cache.get(key); 
  45.         if(node != null){ 
  46.             node.value = value; //更新value值 
  47.             freqInc(node); 
  48.         }else
  49.             //若size达到最大值,则移除频次最小,最久未访问的元素 
  50.             if(size == capacity){ 
  51.                 //因链表是头插法,所以尾结点的前一个节点就是最久未访问的元素 
  52.                 DoubleLinkedList list = freqMap.get(min); 
  53.                 //需要移除的节点 
  54.                 Node deadNode = list.tail.pre; 
  55.                 cache.remove(deadNode.key); 
  56.                 list.removeNode(deadNode); 
  57.                 size--; 
  58.             } 
  59.             //新建一个node,并把node放到频次为 1 的 list 里面 
  60.             Node newNode = new Node(key,value); 
  61.             DoubleLinkedList newList = freqMap.get(1); 
  62.             if(newList == null){ 
  63.                 newList = new DoubleLinkedList(); 
  64.                 freqMap.put(1,newList); 
  65.             } 
  66.             newList.addNode(newNode); 
  67.             cache.put(key,newNode); 
  68.             size++; 
  69.             min = 1;//此时需要把min值重新设置为1 
  70.         } 
  71.  
  72.     } 
  73.  
  74.     //修改频次 
  75.     private void freqInc(Node node){ 
  76.         //先删除node对应的频次list 
  77.         DoubleLinkedList list = freqMap.get(node.freq); 
  78.         if(list != null){ 
  79.             list.removeNode(node); 
  80.         } 
  81.         //判断min是否等于当前node的频次,且当前频次的list为空,是的话更新min值 
  82.         if(min == node.freq && list.isEmpty()){ 
  83.             min ++; 
  84.         } 
  85.         //然后把node频次加 1,并把它放到高频次list 
  86.         node.freq ++; 
  87.         DoubleLinkedList newList = freqMap.get(node.freq); 
  88.         if(newList == null){ 
  89.             newList = new DoubleLinkedList(); 
  90.             freqMap.put(node.freq, newList); 
  91.         } 
  92.         newList.addNode(node); 
  93.     } 
  94.  
  95.  
  96.     private class Node { 
  97.         int key
  98.         int value; 
  99.         int freq = 1; 
  100.         Node pre; 
  101.         Node next
  102.  
  103.         public Node(){ 
  104.  
  105.         } 
  106.  
  107.         public Node(int keyint value){ 
  108.             this.key = key
  109.             this.value = value; 
  110.         } 
  111.     } 
  112.  
  113.     //自实现的一个双向链表 
  114.     private class DoubleLinkedList { 
  115.         Node head; 
  116.         Node tail; 
  117.  
  118.         // 设置两个哨兵节点,作为头、尾节点便于插入和删除操作 
  119.         public DoubleLinkedList(){ 
  120.             head = new Node(); 
  121.             tail = new Node(); 
  122.             head.next = tail; 
  123.             tail.pre = head; 
  124.         } 
  125.  
  126.         //采用头插法,每次都插入到链表的最前面,即 head 节点后边 
  127.         public void addNode(Node node){ 
  128.             node.pre = head; 
  129.             node.next = head.next
  130.             //注意先把head的后节点的前节点设置为node 
  131.             head.next.pre = node; 
  132.             head.next = node; 
  133.         } 
  134.  
  135.         //删除元素 
  136.         public void removeNode(Node node){ 
  137.             node.pre.next = node.next
  138.             node.next.pre = node.pre; 
  139.         } 
  140.  
  141.         //判断是否为空,即是否存在除了哨兵节点外的有效节点 
  142.         public boolean isEmpty(){ 
  143.             //判断头结点的下一个节点是否是尾结点,是的话即为空 
  144.             return head.next == tail; 
  145.         } 
  146.  
  147.     } 
  148.  

方案五:用双向链表嵌套

思路:

可以发现方案三和方案四,都是用 freqmap 来存储频次和它对应的链表之间的关系,它本身也是一个哈希表。这次,我们完全用自己实现的双向链表来代替 freqMap,进一步提高效率。

但是,结构有些复杂,它是一个双向链表中,每个元素又是双向链表。为了便于理解,我把它的结构作图如下:(为了方便,分别叫做外层链表,内层链表)

 

我们把整体看成一个由 DoubleLinkedList组成的双向链表,然后,每一个 DoubleLinkedList 对象中又是一个由 Node 组成的双向链表。像极了 HashMap 数组加链表的形式。

但是,我们这里没有数组,也就不存在哈希碰撞的问题。并且都是双向链表,都有哨兵存在,便于灵活的从链表头部或者尾部开始操作元素。

这里,firstLinkedList 和 lastLinkedList 分别代表外层链表的头尾结点。链表中的元素 DoubleLinkedList 有一个字段 freq 记录了频次,并且按照前大后小的顺序组成外层链表,即图中的 DoubleLinkedList1.freq 大于它后面的 DoubleLinkedList2.freq。

每当有新频次的 DoubleLinkedList 需要添加进来的时候,直接插入到 lastLinkedList 这个哨兵前面,因此 lastLinkedList.pre 就是一个最小频次的内部链表。

内部链表中是由 Node组成的双向链表,也有两个哨兵代表头尾节点,并采用头插法。其实,可以看到内部链表和方案四,图中所示的双向链表结构是一样的,不用多说了。

这样的话,我们就可以找到频次最小,并且最久未访问的元素,即

  1. //频次最小,最久未访问的元素,cache满时需要删除 
  2. lastLinkedList.pre.tail.pre 

于是,代码就好理解了:

  1. public class LFUCache3 { 
  2.  
  3.     public static void main(String[] args) { 
  4.         LFUCache3 cache = new LFUCache3(2); 
  5.         cache.put(1, 1); 
  6.         cache.put(2, 2); 
  7.         // 返回 1 
  8.         System.out.println(cache.get(1)); 
  9.         cache.put(3, 3);    // 去除 key 2 
  10.         // 返回 -1 (未找到key 2) 
  11.         System.out.println(cache.get(2)); 
  12.         // 返回 3 
  13.         System.out.println(cache.get(3)); 
  14.         cache.put(4, 4);    // 去除 key 1 
  15.         // 返回 -1 (未找到 key 1) 
  16.         System.out.println(cache.get(1)); 
  17.         // 返回 3 
  18.         System.out.println(cache.get(3)); 
  19.         // 返回 4 
  20.         System.out.println(cache.get(4)); 
  21.     } 
  22.  
  23.     Map<Integer,Node> cache; 
  24.     /** 
  25.      * 这两个代表的是以 DoubleLinkedList 连接成的双向链表的头尾节点, 
  26.      * 且为哨兵节点。每个list中,又包含一个由 node 组成的一个双向链表。 
  27.      * 最外层双向链表中,freq 频次较大的 list 在前面,较小的 list 在后面 
  28.      */ 
  29.     DoubleLinkedList firstLinkedList, lastLinkedList; 
  30.     int capacity; 
  31.     int size
  32.  
  33.     public LFUCache3(int capacity){ 
  34.         this.capacity = capacity; 
  35.         cache = new HashMap<>(); 
  36.         //初始化外层链表的头尾节点,作为哨兵节点 
  37.         firstLinkedList = new DoubleLinkedList(); 
  38.         lastLinkedList = new DoubleLinkedList(); 
  39.         firstLinkedList.next = lastLinkedList; 
  40.         lastLinkedList.pre = firstLinkedList; 
  41.     } 
  42.  
  43.     //存储具体键值对信息的node 
  44.     private class Node { 
  45.         int key
  46.         int value; 
  47.         int freq = 1; 
  48.         Node pre; 
  49.         Node next
  50.         DoubleLinkedList doubleLinkedList; 
  51.  
  52.         public Node(){ 
  53.  
  54.         } 
  55.  
  56.         public Node(int keyint value){ 
  57.             this.key = key
  58.             this.value = value; 
  59.         } 
  60.     } 
  61.  
  62.     public int get(int key){ 
  63.         Node node = cache.get(key); 
  64.         if(node == nullreturn -1; 
  65.         freqInc(node); 
  66.         return node.value; 
  67.     } 
  68.  
  69.     public void put(int keyint value){ 
  70.         if(capacity == 0) return
  71.         Node node = cache.get(key); 
  72.         if(node != null){ 
  73.             node.value = value; 
  74.             freqInc(node); 
  75.         }else
  76.             if(size == capacity){ 
  77.                 /** 
  78.                  * 如果满了,则需要把频次最小的,且最久未访问的节点删除 
  79.                  * 由于list组成的链表频次从前往后依次减小,故最小的频次list是 lastLinkedList.pre 
  80.                  * list中的双向node链表采用的是头插法,因此最久未访问的元素是 lastLinkedList.pre.tail.pre 
  81.                  */ 
  82.                 //最小频次list 
  83.                 DoubleLinkedList list = lastLinkedList.pre; 
  84.                 //最久未访问的元素,需要删除 
  85.                 Node deadNode = list.tail.pre; 
  86.                 cache.remove(deadNode.key); 
  87.                 list.removeNode(deadNode); 
  88.                 size--; 
  89.                 //如果删除deadNode之后,此list中的双向链表空了,则删除此list 
  90.                 if(list.isEmpty()){ 
  91.                     removeDoubleLinkedList(list); 
  92.                 } 
  93.             } 
  94.             //没有满,则新建一个node 
  95.             Node newNode = new Node(key, value); 
  96.             cache.put(key,newNode); 
  97.             //判断频次为1的list是否存在,不存在则新建 
  98.             DoubleLinkedList list = lastLinkedList.pre; 
  99.             if(list.freq != 1){ 
  100.                 DoubleLinkedList newList = new DoubleLinkedList(1); 
  101.                 addDoubleLinkedList(newList,list); 
  102.                 newList.addNode(newNode); 
  103.             }else
  104.                 list.addNode(newNode); 
  105.             } 
  106.             size++; 
  107.         } 
  108.     } 
  109.  
  110.     //修改频次 
  111.     private void freqInc(Node node){ 
  112.         //从当前频次的list中移除当前 node 
  113.         DoubleLinkedList list = node.doubleLinkedList; 
  114.         if(list != null){ 
  115.             list.removeNode(node); 
  116.         } 
  117.         //如果当前list中的双向node链表空,则删除此list 
  118.         if(list.isEmpty()){ 
  119.             removeDoubleLinkedList(list); 
  120.         } 
  121.         //当前node频次加1 
  122.         node.freq++; 
  123.         //找到当前list前面的list,并把当前node加入进去 
  124.         DoubleLinkedList preList = list.pre; 
  125.         //如果前面的list不存在,则新建一个,并插入到由list组成的双向链表中 
  126.         //前list的频次不等于当前node频次,则说明不存在 
  127.         if(preList.freq != node.freq){ 
  128.             DoubleLinkedList newList = new DoubleLinkedList(node.freq); 
  129.             addDoubleLinkedList(newList,preList); 
  130.             newList.addNode(node); 
  131.         }else
  132.             preList.addNode(node); 
  133.         } 
  134.  
  135.     } 
  136.  
  137.     //从外层双向链表中删除当前list节点 
  138.     public void removeDoubleLinkedList(DoubleLinkedList list){ 
  139.         list.pre.next = list.next
  140.         list.next.pre = list.pre; 
  141.     } 
  142.  
  143.     //知道了它的前节点,即可把新的list节点插入到其后面 
  144.     public void addDoubleLinkedList(DoubleLinkedList newList, DoubleLinkedList preList){ 
  145.         newList.pre = preList; 
  146.         newList.next = preList.next
  147.         preList.next.pre = newList; 
  148.         preList.next = newList; 
  149.     } 
  150.  
  151.     //维护一个双向DoubleLinkedList链表 + 双向Node链表的结构 
  152.     private class DoubleLinkedList { 
  153.         //当前list中的双向Node链表所有频次都相同 
  154.         int freq; 
  155.         //当前list中的双向Node链表的头结点 
  156.         Node head; 
  157.         //当前list中的双向Node链表的尾结点 
  158.         Node tail; 
  159.         //当前list的前一个list 
  160.         DoubleLinkedList pre; 
  161.         //当前list的后一个list 
  162.         DoubleLinkedList next
  163.  
  164.         public DoubleLinkedList(){ 
  165.             //初始化内部链表的头尾节点,并作为哨兵节点 
  166.             head = new Node(); 
  167.             tail = new Node(); 
  168.             head.next = tail; 
  169.             tail.pre = head; 
  170.         } 
  171.  
  172.         public DoubleLinkedList(int freq){ 
  173.             head = new Node(); 
  174.             tail = new Node(); 
  175.             head.next = tail; 
  176.             tail.pre = head; 
  177.             this.freq = freq; 
  178.         } 
  179.  
  180.         //删除当前list中的某个node节点 
  181.         public void removeNode(Node node){ 
  182.             node.pre.next = node.next
  183.             node.next.pre = node.pre; 
  184.         } 
  185.  
  186.         //头插法将新的node插入到当前list,并在新node中记录当前list的引用 
  187.         public void addNode(Node node){ 
  188.             node.pre = head; 
  189.             node.next = head.next
  190.             head.next.pre = node; 
  191.             head.next = node; 
  192.             node.doubleLinkedList = this; 
  193.         } 
  194.  
  195.         //当前list中的双向node链表是否存在有效节点 
  196.         public boolean isEmpty(){ 
  197.             //只有头尾哨兵节点,则说明为空 
  198.             return head.next == tail; 
  199.         } 
  200.     } 
  201.  
  202.  

由于,此方案全是链表的增删操作,因此时间复杂度可到 O(1)。

 

结语终于总结完了,其实,感觉思想搞明白了,代码实现起来就相对容易一些。但是,还是需要多写,多实践。过段时间再来回顾一下~

本文转载自微信公众号「 烟雨星空」,可以通过以下二维码关注。转载本文请联系 烟雨星空公众号。

 

 

责任编辑:武晓燕 来源: 烟雨星空
相关推荐

2020-11-18 09:30:29

图片懒加载前端浏览器

2023-05-07 08:00:32

2013-05-13 11:25:02

WAFWeb应用防火墙WAF绕过

2017-07-04 16:34:33

边缘计算方式

2016-12-07 10:02:54

移动应用开发底部导航android

2010-08-13 13:25:53

Flex页面跳转

2023-09-07 19:14:05

2010-01-25 17:53:35

Android Lis

2013-09-03 10:01:13

服务器机房数据

2012-02-09 09:00:54

汇编语言

2009-02-27 08:45:27

Unix入门

2011-02-28 13:51:30

Spring事物配置

2009-06-19 18:26:38

Spring事务配置

2009-08-22 17:08:02

家庭智能布线综合布线连接

2010-08-27 09:10:15

网络隐私

2022-08-18 09:38:02

Spring跨域

2023-02-27 22:03:06

数据库内存RocketMQ

2011-11-25 10:25:27

SpringJava

2009-10-23 14:11:06

linux常用软件

2022-10-31 16:58:14

物联网
点赞
收藏

51CTO技术栈公众号