4
头图

LRU cache mechanism

Topic description: Design and implement an LRU (least recently used) cache mechanism using the data structures you have mastered.
Implement the LRUCache class:

  • LRUCache(int capacity) Initializes the LRU cache with a positive integer as the capacity capacity
  • int get(int key) Returns the value of the key if the key key exists in the cache, otherwise -1.
  • void put(int key, int value) If the key already exists, change its data value; if the key does not exist, insert the set of "key-value". When the cache capacity reaches the upper limit, it should delete the oldest unused data values before writing new data to make room for new data values.

Advanced: Can you do both operations in O(1) time complexity?

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/lru-cache/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: LinkedHashMap
Because it allows the use of existing data structures, LinkedHashMap supports it, so you can directly inherit LinkedHashMap. Of course, this is a lazy approach. If you understand the implementation of LinkedHashMap, you can follow the implementation.
import java.util.LinkedHashMap;
import java.util.Map;

public class LeetCode_146 {
    public static void main(String[] args) {
        // 测试用例
        LRUCache lRUCache = new LRUCache(2);
        lRUCache.put(1, 1); // 缓存是 {1=1}
        lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
        lRUCache.get(1);    // 返回 1
        lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
        lRUCache.get(2);    // 返回 -1 (未找到)
        lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
        lRUCache.get(1);    // 返回 -1 (未找到)
        lRUCache.get(3);    // 返回 3
        lRUCache.get(4);    // 返回 4
    }
}

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

    /**
     * 移除最久未使用的数据的条件:当缓存容量达到上线
     *
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }
}
[Daily Message] have been fighting for a lifetime is just a diaosi, and maybe the salted fish turns over and is just a salted fish that has turned its face, but at least we have the self-respect for dreaming, instead of leaving a sentence of "effort is useless" and feel at ease live on.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!