队列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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)