面试题-手写LRU

45 阅读1分钟

什么事LRU 就是least recently used 最近最少使用的元素 我用类的方式加map实现, 面试的时候就拿这版,超快的 记得有一次面试我手写这个,我用的数组的push,unshift方法,来回放进去取出来,还要查找数组中有没有存在过当前设置的值,搞到后面翻了车,这版简单多了,30行代码搞定 比较简洁的代码如下

class LRUCache {

    map;
    length;
    constructor(length){
        this.map = new Map();
        this.length = length;
    }
    has(key) {
        return this.map.has(key);
    }
    get(key){
        if(!this.map.has(key)) return null;
        const value = this.map.get(key);
        this.map.delete(key);
        this.map.set(key,value);
        return value;
    }
    set(key,value){
        if(this.map.has(key){
            this.map.delete(key)
        }
        this.map.set(key,value);
        if(this.map.size > this.length) {
            console.log(this.map.keys() // map中key值全部取出来,四个迭代器对象
            this.map.delete(this.map.keys().next().value)
            
        }
    }
 }
let l = new LRUCache(3)
l.set(3,333)
l.set(4,444)
l.set(5,555)
l.set(6,666)
console.log(l)