146. LRU Cache

49 阅读1分钟

146. LRU Cache

Map 的 key 是有序的 通常重新设置的值会被置于 最前 map.keys().next().value 会返回最近一直没有被用到的 key

解题思路

  1. get 获取的情况 通过 map.has(key) 判断有没有 如果有的话 需要先删除 重新设置 key,没有直接返回 -1
  2. put 的情况 如果有 直接删除 如果超出的容量需要删除末尾的 key 即 map.delete(map.keys().next().value),最后再 map.set(key, 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) {
    // 如果有的话需要先保存后 将key重置到最前
    if(this.map.has(key)) {
       const val = this.map.get(key)
       this.map.delete(key)
       this.map.set(key, val)
       return val
    }
    return -1
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    // 如果有相关的key
    if(this.map.has(key)) {
        this.map.delete(key)
    // 容量满了需要删除一个最近没有用到的 key
    } else if(this.capacity === this.map.size) {
        const delKey = this.map.keys().next().value
        this.map.delete(delKey);
    }
    
    this.map.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)
 */