LRU缓存机制

Posted yonezu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

 

以上是关于LRU缓存机制的主要内容,如果未能解决你的问题,请参考以下文章

146. LRU 缓存机制

算法:LRU缓存机制

精选力扣500题 第2题 LeetCode 146. LRU 缓存机制 c++详细题解

leetcode146. LRU缓存机制

LRU(最近最少使用)缓存机制

LRU 缓存机制及 3 种简单实现