zoukankan      html  css  js  c++  java
  • LRU最少使用

      通过继承LinkedHashMap实现LRU:

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    
        private int size;
    
        public LRUCache(int size) {
            super((int) Math.ceil(size / 0.75) + 1, 0.75f, true);
            this.size = size;
        }
    
        protected boolean removeEldestEntry(Map<K, V> eldest) {
            return size() > size;
        }
    }

    import com.alibaba.fastjson.JSON;
    
    public class LRUMain {
    
        public static void main(String[] args) {
            LRUCache lruCache = new LRUCache(10);
            lruCache.put("1", "1");
            lruCache.put("2", "2");
            lruCache.put("3", "3");
            lruCache.put("4", "4");
            lruCache.put("5", "5");
            lruCache.put("6", "6");
            System.out.println(JSON.toJSONString(lruCache));
            lruCache.get("2");
            System.out.println(JSON.toJSONString(lruCache));
            lruCache.get("5");
            lruCache.get("5");
            lruCache.get("5");
            lruCache.get("5");
            System.out.println(JSON.toJSONString(lruCache));
        }
    }

    {"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6"}
    {"1":"1","3":"3","4":"4","5":"5","6":"6","2":"2"}
    {"1":"1","3":"3","4":"4","6":"6","2":"2","5":"5"}

    通过双向链表+map可以实现LRU

  • 相关阅读:
    LeetCode Power of Three
    LeetCode Nim Game
    LeetCode,ugly number
    LeetCode Binary Tree Paths
    LeetCode Word Pattern
    LeetCode Bulls and Cows
    LeeCode Odd Even Linked List
    LeetCode twoSum
    549. Binary Tree Longest Consecutive Sequence II
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/use-D/p/12622681.html
Copyright © 2011-2022 走看看