146. LRU 缓存(中)

题目

法一、Map

  • 对于超出容量时,删除最久未使用的关键字:在进行put和get时,只要存在就先删再重新放入map,保证了最久未使用的关键字处于map的第一个
/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.map = new Map()
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    //Map查询,如果有key先删再重新放入map(便于处理最久未动的key)返回value,否则返回-1
    if (this.map.has(key)){
        let temp = this.map.get(key)
        this.map.delete(key);
        this.map.set(key,temp);
        return temp;
    }else{
        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); 
    }
    this.map.set(key,value);
    if(this.map.size > this.capacity){//超出容量,去除map中的第一个key、value
        this.map.delete(this.map.keys().next().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)
 */

法二、双向链表

posted @ 2025-01-08 12:39  Frommoon  阅读(6)  评论(0)    收藏  举报