实现LRU缓存淘汰算法

实现LRU缓存淘汰算法,第1张

实现LRU缓存淘汰算法

LRU:缓存淘汰算法,最近最少使用淘汰

队列
class LRUCache{
    constructor(size){
        this.capacity = size;
        this.cache = new Map();
    }

    //  队列 先前先出  对头进  队尾出

    get(key){
        if(this.cache.has(key)){
            let temp = this.cache.get(key);
            // 删除这个值
            this.cache.delete(key);
            // 将这个值加到队尾
            this.cache.set(key,temp);
            return temp;
        }
        return -1;
    }
    put(key,value){
        if(this.cache.has(key)){
            // 有删除
            this.delete(key);
        }else if(this.cache.size >= this.capacity){
            // 无 删除队头
            this.cache.delete(this.cache.keys().next().value);
        }
            // 加到队尾
        this.cache.set(key,value);
    }
}
let lru = new LRUCache(4)
lru.put(1,1);
lru.put(2,2);
lru.put(3,3);
lru.put(4,4);
console.log(lru.cache);
lru.put(5,5);
console.log(lru.cache);
lru.get(3)
console.log(lru.cache);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5695394.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存