leetCode 146题 LRU缓存

98 阅读1分钟

今天休息,刷短视频看到了渡一在讲LRU算法,就去leetcode回顾了一下,是一个比较经典的面试题,LRU是vue中keep-alive的原理,也是想着就敲了一下回顾看看。

两种解法:1.利用map特性,map的加入和删除和这个题目不谋而合。

var LRUCache = function (capacity) {
this.limit = capacity;
this.cache = new Map();
};

LRUCache.prototype.get = function (key) {
let tmp;

if (this.cache.has(key)) {
    tmp = this.cache.get(key);

    this.cache.delete(key);
    this.cache.set(key, tmp);
}

return tmp ?? -1;
};

LRUCache.prototype.put = function (key, value) {
if (this.cache.has(key)) {
    this.cache.delete(key);
}
this.cache.set(key, value);

if (this.cache.size > this.limit) {
    this.cache.delete(this.cache.keys().next().value);
}
};

2.构造数据结构,一步步去写,这里看了评论的题解写的hhh。

class Node{
constructor(key = 0 , value = 0){
    this.key = key;
    this.value = value;
    this.prev = null;
    this.next = null;
}
}

class LRUCache {
    constructor(capacity){
        this.capacity = capacity;
        this.dummy = new Node();
        this.dummy.prev = this.dummy;
        this.dummy.next = this.dummy;
        this.keyToNode = new Map();
    }

getNode(key){
    if(!this.keyToNode.has(key)){
        return null
    }
    const node = this.keyToNode.get(key)
    this.remove(node);
    this.pushFront(node);
    return node;
}

get(key){
    const node = this.getNode(key);
    return node ? node.value: -1;
}

put(key , value){
    let node = this.getNode(key);
    if (node){
        node.value = value;
        return
    }
    node = new Node(key,value)
    this.keyToNode.set(key,node);
    this.pushFront(node);
    if (this.keyToNode.size > this.capacity) {
        const backNode = this.dummy.prev;
        this.keyToNode.delete(backNode.key);
        this.remove(backNode);
    }
}
remove(x){
    x.prev.next = x.next;
    x.next.prev = x.prev
}

pushFront(x) {
    x.prev = this.dummy;
    x.next = this.dummy.next;
    x.next.prev = x
    x.prev.next = x
}
}