Hot100【十一】:146. LRU 缓存

Hot100【十一】:146. LRU 缓存_第1张图片

// 继承LinkedHashMap,重写removeEldestEntry(Map.Entry eldest)
class LRUCache
        extends LinkedHashMap<Integer, Integer> { // 1.继承linkedHashMap

    private int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true); // 2.super构造方法(容量、 hash因子、 按顺序排列)
        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
    public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { // 3. 重写removeEldestEntry
        return size() > capacity;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

你可能感兴趣的:(#,Hot100算法,算法,hot100,LRU缓存)