设计和实现一个 LRU (最近最少使用) 缓存机制

724 阅读1分钟

设计和实现一个 LRU (最近最少使用) 缓存机制

思路:

  1. 它应该支持以下操作: 获取数据 get 和 写入数据 put 。
  2. 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
  3. 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

方案一 直接继承LinkHashMap的方式

public class LRUCache extends LinkedHashMap<Integer,Integer> {

private int capacity;

public LRUCache(int capacity){
    super(capacity,0.75f,true);
    this.capacity = capacity;
}

public  int get(int key){
    return super.getOrDefault(key,-1);
}

public void put(int key,int value){
    super.put(key,value);
}

@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
    return size() > capacity;
}

}

方案二 双链表+hashMap

public class LRUCacheNormal {
    private int capacity;
    private HashMap<Integer,Integer> map;
    private DoubleLink cache;

    public LRUCacheNormal(int capacity) {
        // 初始化 LRU cache 的数据
        this.capacity = capacity;
        this.map = new HashMap<>();
        this.cache = new DoubleLink();
    }

    public int get(int key) {
        if (!map.containsKey(key))
            return -1;
        int val = map.get(key).intValue();
        put(key, val);
        return val;
    }

    public void put(int key, int val) {
        // 先把新节点 x 做出来
        Node x = new Node(key, val);

        if (map.containsKey(key)) {
            // 删除旧的,新的插到头部
            cache.remove(new Node(key, map.get(key)));
            cache.addFirst(x);
            // 更新 map 中对应的数据
            map.put(key, x.val);
        } else {
            if (capacity == cache.size()) {
                // 删除链表最后一个
                Node last = cache.removeLast();
                map.remove(last.key);
            }
            // 直接添加到头部即可
            cache.addFirst(x);
            map.put(key, x.val);
        }
    }

    class DoubleLink {
        private Node head,tail;
        private int size;

        public  DoubleLink(){
            head = new Node(0, 0);
            tail = new Node(0, 0);
            head.next = tail;
            tail.prev = head;
            size = 0;
        }

        public void addFirst(Node x) {
            x.next = head.next;
            x.prev = head;
            head.next.prev = x;
            head.next = x;
            size++;
        }

        public void remove(Node x) {
            x.prev.next = x.next;
            x.next.prev = x.prev;
            size--;
        }

        public Node removeLast() {
            if (tail.prev == head)
                return null;
            Node last = tail.prev;
            remove(last);
            return last;
        }

        public int size() {
            return size;
        }
    }

    class Node {
        public int key, val;
        public Node next, prev;
        public Node(int k, int v) {
            this.key = k;
            this.val = v;
        }
    }
}