Leetcode刷题(第146题)——LRU缓存

x33g5p2x  于2022-03-14 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(138)

一、题目

二、示例

三、思路
本题采用hash表,以及迭代器,当每一次访问的元素都从中删除,然后再从后面加入。当put进一个元素时,此时应该判断该元素是否存在,如果存在,则先删除,然后再进行插入。最后使用迭代器删除第一个元素。
四、代码

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

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if(this.cache.has(key)) {
        let temp = this.cache.get(key)
        this.cache.delete(key)
        this.cache.set(key, temp)
        return temp
    }else {
        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)
    this.cache.set(key, value)
    if(this.cache.size > this.length) {
        this.cache.delete(this.cache.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)
 */

五、总结

相关文章

微信公众号

最新文章

更多