简单的说,就是用链表特性,表示顺序,1-2-3-4-5 如果6来了 就是 1-2-3-4-5-6 但是超过了,就 变成吗了2-3-4-5-6 然后 如果 4来了,2-3-5-6-4,就把原来的4 从 3-5 中指向修改一下
原理:
https://baijiahao.baidu.com/s?id=1633118537743651176&wfr=spider&for=pc
image.png
js实现算法:

  1. /**
  2. * * 题目名称:实现lru算法
  3. * * 题目地址:https://www.yuque.com/damowangdexiaogenban/geocaz/rmvnlx
  4. *
  5. * 维护一个map,提供 get 和 put 方法,并且限定 max 数量。
  6. 使用时,get 可以标记某个元素是最新使用的,提升它去第一项。put 可以加入某个key-value,但需要判断是否已经到最大限制 max
  7. 若未到能直接往数组第一项里插入
  8. 若到了最大限制 max,则需要淘汰数据尾端一个元素。
  9. */
  10. // * 思路: 时间复杂度 O(1),那就不能数组遍历去查找 key 值。可以用 ES6 的 Map 来解了,因为 Map 既能保持键值对,还能记住插入顺序。
  11. class LRUCache {
  12. constructor(capacity) {
  13. this.capacity = capacity
  14. this.cache = new Map()
  15. }
  16. get (key) {
  17. // 如果存在值,就把原来的值取出来,在重新set一下就返回到了最后面
  18. if (this.cache.has(key)) {
  19. let temp = this.cache.get(key)
  20. this.cache.delete(key)
  21. this.cache.set(key, temp)
  22. return temp
  23. }
  24. return -1
  25. }
  26. put (key, value) {
  27. if (this.cache.has(key)) {
  28. // 存在就先删除,在更新
  29. this.cache.delete(key)
  30. } else if (this.cache.size >= this.capacity) {
  31. //缓存超过最大值就删除最近没使用的
  32. // this.cache.keys().next().value 取出 map中的 第一个key
  33. // map是由顺序的所以 就删除了最遥远的第一个
  34. this.cache.delete(this.cache.keys().next().value)
  35. }
  36. // 设置值
  37. this.cache.set(key, value)
  38. }
  39. }
  40. // 测试用例
  41. let cache = new LRUCache(2 /* 缓存容量 */);
  42. cache.put(1, 1);
  43. cache.put(2, 2);
  44. console.log(cache.get(1)); // 返回 1
  45. cache.put(3, 3); // 该操作会使得密钥 2 作废
  46. console.log(cache.get(2)); // 返回 -1 (未找到)
  47. cache.put(4, 4); // 该操作会使得密钥 1 作废
  48. console.log(cache.get(1)); // 返回 -1 (未找到)
  49. console.log(cache.get(3)); // 返回 3
  50. console.log(cache.get(4)); // 返回 4

使用案例