ID:146.LRU 缓存

42 阅读1分钟

题目链接

思路

用 Map 来存储所有的键值对。注意:

  • get 的时候要先删除再添加
  • put 的时候利用 Map 底层类似于链表的原理,通过迭代器取到第一个值,当缓存数量超限时将其清除
var LRUCache = function (capacity) {
  this.capacity = capacity;
  this.cache = new Map();
};

/**
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function (key) {
  let val;
  if (this.cache.has(key)) {
    val = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, val);
  }
  return val ?? -1;
};

/**
 * @param {number} key
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function (key, value) {
  if (this.cache.has(key)) this.cache.delete(key);
  this.cache.set(key, value);
  if (this.cache.size > this.capacity) {
    this.cache.delete(this.cache.keys().next().value);
  }
};