zoukankan      html  css  js  c++  java
  • LRU缓存机制

     方法一:Map加双向链表

    class LRUCache {
    
        class Node {
            public int key, val;
            Node pre,next;
            public Node() {}
            public Node(int k, int v) {
                key = k;
                val = v;
            }
        }
        private Map<Integer,Node> map = new HashMap<>();
        private Node root, tail;
        private int num, capacity;
    
        public LRUCache(int capacity) {
            this.capacity = capacity;
            this.num = 0;
            root = new Node();
            tail = new Node();
            root.next = tail;
        }
        public int get(int key) {
            Node n = map.get(key);
            if(n == null) return -1;
            removeToHead(n);
            return n.val;
        }
        
        public void put(int key, int value) {
            Node n = map.get(key);
            if(n == null) {
                Node newNode = new Node(key,value);
                if(num == capacity) {
                    Node del = removeLast();
                    map.remove(del.key);
                    num--;
                }
                addToHead(newNode);
                map.put(key,newNode);
                num++;
            } else {
                n.val = value;
                removeToHead(n);
            }
        }
        private void addToHead(Node n) {
            root.next.pre = n;
            n.next = root.next;
            root.next = n;
            n.pre = root;
        }
        private void deleteNode(Node n) {
            n.pre.next = n.next;
            n.next.pre = n.pre;
        }
        private void removeToHead(Node n) {
            deleteNode(n);
            addToHead(n);
        }
        private Node removeLast() {
            Node res = tail.pre;
            deleteNode(res);
            return res;
        }
    
    }

    方法二:LinkedHashMap

    class LRUCache {
        int capacity;
        LinkedHashMap<Integer, Integer> cache;
    
        public LRUCache(int capacity) {
            this.capacity = capacity;
            cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return cache.size() > capacity;
                }
            };
        }
    
        public int get(int key) {
            return cache.getOrDefault(key, -1);
        }
    
        public void put(int key, int value) {
            cache.put(key, value);
        }
    }
  • 相关阅读:
    伟大的微软,太智能了
    ASP.NET MVC中的统一化自定义异常处理
    去除无用的文件查找路径
    关于easyUI的一些js方法
    easyUI小技巧-纯干货
    easyui tree tabs
    ueditor初始化
    多图联动
    饼图tooltip
    配色
  • 原文地址:https://www.cnblogs.com/yonezu/p/13368780.html
Copyright © 2011-2022 走看看