【leetcode】146.LRU 缓存

183 阅读1分钟

image.png

非常经典的一道题,没啥难度,主要就是考察如何构建数据结构
使用used来存储最近使用的元素,队头就是最久没有使用过的元素了

/**
 * @param {number} capacity
 */
var LRUCache = function (capacity) {
    this.capacity = capacity
    this.used = []
    this.map = new Map()
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function (key) {
    if (this.map.has(key)) {
        let index = this.used.indexOf(key)
        // 使用到了当前的key,那么就要更新used
        this.used.splice(index, 1)
        this.used.push(key)
        return this.map.get(key)
    }
    return -1
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function (key, value) {
    if (this.map.has(key)) {
        // 已经存在key,那就需要更新
        let index = this.used.indexOf(key)
        this.used.splice(index, 1)
    } 
    if (this.used.length === this.capacity) {
        // 容量达到上限,删除map里面的数据
        // used 在外面进行处理
        let delKey = this.used.shift()
        this.map.delete(delKey)
    }
    this.map.set(key, value)
    this.used.push(key)
};

使用map的性质来解决这一题,get元素的时候,如果存在,就把当前的k-v删除,然后更新到最末尾
map的有序性,最先插入的元素可以通过map.keys().next().value找到

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

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function (key) {
    if (this.map.has(key)) {
        let value = this.map.get(key)
        // 删除
        this.map.delete(key)
        // 更新位置
        this.map.set(key, value)
        return value
    }
    return -1
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function (key, value) {
    if (this.map.has(key)) {
        this.map.delete(key)
    }
    if (this.map.size === this.capacity) {
        // next方法来迭代 keys,然后取出第一个key来进行删除
        let delKey = this.map.keys().next().value
        this.map.delete(delKey)
    }
    this.map.set(key, value)
};