题解 | #设计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)
 */

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务