1. 程式人生 > 實用技巧 >LRU快取機制

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);
    }
}