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

设计LRU缓存结构

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

/**
 * @param {number} capacity
 */
var Solution = function (capacity) {
  this.capacity = capacity;
  // 使用map数据结构构造
  this.map = new Map();
};

/**
 * @param {number} key
 * @return {number}
 */
Solution.prototype.get = function (key) {
  // write code here
  // get分为可以获取到和获取不到
  if (this.map.has(key)) {
    // 如果存在这个key,将value获取出来
    let value = this.map.get(key);
    // 删除原本位置的key
    this.map.delete(key);
    // 将最新的key放在map的最后
    this.map.set(key, value);
    return value
  } else {
    return -1;
  }
};

/**
 * @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) {
    let last = Array.from(this.map.keys())[0]
    this.map.delete(last);
  }
};

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

#算法#
全部评论

相关推荐

2025-12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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