栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

实现LRU缓存淘汰算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现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);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号