LRU缓存

目录

LeetCode-146


LeetCode-146

设计并实现一个满足LRU(最近最少使用)缓存约束的数据结构。

java 复制代码
class LRUCache {
    // 缓存结构
    private final Cache<Integer, Integer> cache;

    public LRUCache(int capacity) {
        cache = new Cache<>(capacity);
    }

    // 从缓存中获取值
    public int get(int key) {
        Integer value = cache.get(key);
        return value == null ? -1 : value;
    }

    // 往缓存中添加节点
    public void put(int key, int value) {
        cache.put(key, value);
    }
}

// 利用LinkedHashMap的特性来实现
class Cache<K, V> extends LinkedHashMap<K, V> {

    private static final int DEFAULT_CAPACITY = 1 << 8;

    private final int capacity;

    public Cache() {
        this(DEFAULT_CAPACITY);
    }

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

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