chunbin1 / blog

git actions + dumijs 写的博客
https://chunbin1.github.io/blog/
0 stars 0 forks source link

146. LRU 缓存 #27

Open chunbin1 opened 2 years ago

chunbin1 commented 2 years ago

思路: 利用Map有顺序的原理

  1. get的时候从map中删除,再塞回去。
  2. put的时候先把有的delete掉,然后如果超过缓存最大值,就删除第一个
    
    /**
    * @param {number} capacity
    */
    var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.map = new Map();
    };

/**

/**

/**

chunbin1 commented 2 years ago

使用数组来记录key

class Cache {
    constructor(size = 1) {
        this.size = size
        this.keyArr = []
        this.keyValueMap = new Map()
    }

    get(key) {
        debugger
        const val = this.keyValueMap.get(key)
        if (val) {
            const idx = this.keyArr.indexOf(key)
            this.keyArr.splice(idx, 1)
            this.keyArr.unshift(key)
            return val
        }
        return -1
    }

    put(key, val) {
        if (this.keyValueMap.size >= this.size) {
            // 缓存淘汰
            const deleteKey = this.keyArr.pop()
            this.keyValueMap.delete(deleteKey)

        }
        // 缓存进入
        this.keyValueMap.set(key, val)
        this.keyArr.push(key)
    }
}