码迷,mamicode.com
首页 > 其他好文 > 详细

LRU缓存机制

时间:2020-07-23 23:01:59      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:链表   hashmap   ast   cap   class   new   div   override   mic   

技术图片

 

 方法一: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);
    }
}

 

LRU缓存机制

标签:链表   hashmap   ast   cap   class   new   div   override   mic   

原文地址:https://www.cnblogs.com/yonezu/p/13368780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!