2022年8月20日(NC93 设计LRU缓存结构)

854 阅读1分钟

首发于 语雀@blueju

题目

www.nowcoder.com/practice/5d…

代码

/**
 * @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
  const cache = this.cache;
  if (cache.has(key)) {
    const value = cache.get(key);
    cache.delete(key);
    cache.set(key, value);
    return value;
  } else {
    return -1;
  }
};

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

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

心得

其实这一题并不难,主要在两点:

  • 知道 LRU 是啥概念
  • 如何更新缓存优先级(尤其是 set 时如何将取出最少使用的那个值的 key)

像本文中使用的是 JavaScript 中的 Map,首先我们要知道 Map 是有顺序,按输入顺序排序,所以我们删除最少使用的那个值时,应该是删除 Map 的头(而不是末尾)。 因此从这一题中我也了解到我对 Map 还并没有想象中的那么熟悉。