LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”.

    1. 示例:
    2. LRUCache cache = new LRUCache(2); // 缓存容器
    3. cache.put(1, 1)
    4. cache.put(2, 2)
    5. cache.get(1) // 返回 1
    6. cache.put(3, 3) // 该操作会得到密钥 2 作废
    7. cache.get(2) // 返回 -1 ,未找到
    8. cache.put(4, 4) // 该操作会得到密钥 1 作废
    9. cache.get(1) // 返回 -1 ,未找到
    10. cache.get(3) // 返回 3
    11. cache.get(4) // 返回 4
    // 一个 Map 对象在迭代时会根据对象中元素插入顺序来进行
    // 新添加的元素会被插入到 Map 的末尾,整个栈倒序查看
    class LRUCache {
        constructor(capacity) {
            // 密钥
            this.secretKey = new Map()
            // 容量
            this.capacity = capacity
        }
        get(key) {
            if (this.secretKey.has(key)) {
                const tempSecreKey = this.secretKey.get(key)
                this.secretKey.delete(key)
                this.secretKey.set(key, tempSecreKey)
                return tempSecreKey
            } else return -1
        }
        put(key, value) {
            // 若 key 存在,则修改,提升位置
            if (this.secretKey.has(key)) {
                this.secretKey.delete(key)
                this.secretKey.set(key, value)
            }
            // 不存在,容器未满
            else if (this.secretKey.size < this.capacity) {
                this.secretKey.set(key, value)
            }
            // 若不存在,容器已满,添加新key,删除旧 key
            else {
                this.secretKey.set(key, value)
                // 删除 Map 的第一个元素,即为最长时间未使用的
                this.secretKey.delete(this.secretKey.keys().next().value)
            }
        }
    }
    
    let cache = new LRUCache(2);
    cache.put(1, 1);
    cache.put(2, 2);
    console.log("cache.get(1)", cache.get(1))// 返回  1
    cache.put(3, 3);// 该操作会使得密钥 2 作废
    console.log("cache.get(2)", cache.get(2))// 返回 -1 (未找到)
    cache.put(4, 4);// 该操作会使得密钥 1 作废
    console.log("cache.get(1)", cache.get(1))// 返回 -1 (未找到)
    console.log("cache.get(3)", cache.get(3))// 返回  3
    console.log("cache.get(4)", cache.get(4))// 返回  4
    

    Map 数据结构新知识:
    image.png