Day2-链表2(LRU缓存)

142 阅读1分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

概念

LRU:least recent use,最少最近使用

  • 1->2->3->4,现在5插入,将4挤出,就变成5->1->2->3
  • 使用了一次2,变成2->5->1->3

Map和Set

解题之前,先看一下Map,顺便也说下Set image.png 这部分内容与本题无关,可以略过

Set

Set实例的方法分为两大类:操作方法(用于操作数据)和遍历方法(用于遍历成员)。 image.png

由于Set结构没有键名,只有键值(或者说键名和键值是同一个值),所以key方法和value方法的行为完全一致。
Set是一组key的集合,所以不存value,由于key不能重复,所以Set中没有重复的key。

Set应用于数组去重: image.png

Map

Map和对象的区别
1.Map具有size属性,可以获取所有元素的数量
2.Map是可迭代的,遍历更为方便,性能上更好
3.删除或添加元素,建议用Map
4.Map的key可以是任意数据类型

为什么引入Map?
因为对象的健只能是字符串,而Map的健可以是任意类型。 image.png

力扣146 LRU缓存

image.png image.png

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.cache = new Map()
    this.max = capacity
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if (this.cache.has(key)) {
        let tmp = this.cache.get(key)
        this.cache.delete(key)
        this.cache.set(key, tmp)
        return tmp
    }
    return -1
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    if (this.cache.has(key)) {
        this.cache.delete(key)
    } else if(this.cache.size >= this.max){
        // 超出长度新增,要淘汰掉第一个数据
        this.cache.delete(this.cache.keys().next().value)
    }
    this.cache.set(key,value)
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */