题解 | #设计LRU缓存结构#

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

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

/** 
 * @param {number} key
 * @return {number}
 */
Solution.prototype.get = function(key) {
    if(!this.map.has(key)) {
        return -1
    }
    const value = this.map.get(key)
    // 删除之前的数据
    this.map.delete(key)
    //再把数据加进去
    this.map.set(key,value)
    return value
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
Solution.prototype.set = function(key, value) {
    // 如果之前有这条数据,就删掉
    if(this.map.has(key)) {
        this.map.delete(key)
    }
     // 统一变成添加行为
     this.map.set(key,value)
     // 如果超出最大长度
     if(this.map.size > this.capacity) {
        const firstKey = this.map.keys().next().value
        this.map.delete(firstKey)
     }
};

module.exports = {
 Solution : Solution
};

/**
 * Your Solution object will be instantiated and called as such:
 * var solution = new Solution(capacity)
 * var output = solution.get(key)
 * solution.set(key,value)
 */

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-21 17:59
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务