LeetCode LRU缓存算法

LRU 是 Least Recently Used 的缩写,即最近最少使用,是一种常用的页面置换算法,选择内存中最近最久未使用的页面予以淘汰。

可用的 NodeJS 库见node-lru-cache

然怎么使用 JS 简单写一个?类似的题目见 LeetCode 146 LRU 缓存机制,进阶要求时间复杂度 O(1) 。

思路

解法:维护一个数组,提供 get 和 put 方法,并且限定 max 数量。

使用时,get 可以标记某个元素是最新使用的,提升它去第一项。put 可以加入某个key-value,但需要判断是否已经到最大限制 max

  • 若未到能直接往数组第一项里插入
  • 若到了最大限制 max,则需要淘汰数据尾端一个元素。

通过维护一个Map对象,因为 Map 既能保持键值对,还能记住插入顺序。

 

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
  this.catch = new Map()
  this.capacity = capacity
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
  if(this.catch.has(key)) {
    // 存在即更新
    let temp = this.catch.get(key)
    this.catch.delete(key)   // 从底部删除
    this.catch.set(key, temp)  // 插入到顶部
    return temp
  }
  // 不存在返回-1
  return -1
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
  if(this.catch.has(key)) {
    // 存在就更新,,先删除后加入
    this.catch.delete(key)
  }else if(this.catch.size >= this.capacity) {  // 不存在就需要加入
    // 先判断内存是否超过最大值
    this.catch.delete(this.catch.keys().next().value)
  }
  this.catch.set(key, value)
};

 

posted @ 2020-11-18 16:39  leahtao  阅读(230)  评论(0编辑  收藏  举报