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

设计LRU缓存结构

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

/**
 * @param {number} capacity
 */
var Solution = function(capacity) {
 // write code here
 this.cache = new Map();
 this.capacity = capacity;
};

/** 
 * @param {number} key
 * @return {number}
 */
Solution.prototype.get = function(key) {
 // write code here
 if(this.cache.has(key)){
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key,value);
    return value;
 }
 return -1;
 
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
Solution.prototype.set = function(key, value) {
 // write code here
 if(this.cache.has(key)){
    this.cache.delete(key);
 }
 this.cache.set(key,value);
 if(this.cache.size>this.capacity){
    const keys = this.cache.keys();
    const array = [...keys];
    const v = array[0];
    this.cache.delete(v);
 }
};

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)
 */

全部评论

相关推荐

不愿透露姓名的神秘牛友
09-30 19:49
起名星人:蛮离谱的,直接要求转投销售
投递汇川技术等公司10个岗位
点赞 评论 收藏
分享
一颗宏心:华为HR晚上过了十二点后还给我法消息。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务