LRU cache algorithm

foreword

Go directly to the algorithm question:

image.png
LRU is the least recently used algorithm, which is a memory data elimination strategy. In actual development, when the memory is insufficient, the least recently used data needs to be eliminated. So how is this algorithm implemented?

text

There are many ways of thinking about this question. Here, the data structure of map is mainly used . Why use map? Because the key of the map can be of any type , and its storage is ordered , we can use the nature of the map to clarify the thinking of solving the problem.

train of thought

  1. Define a map data structure and a variable for storage capacity .
  • With the help of the size attribute of the map , it is easy to know whether it has reached the storage threshold . When the threshold is reached, the least recently used element will be deleted ( delete ), and the new value will be put ( set ) into the map.
  1. Two methods are defined on the prototype of this method , which are access to elements in the map ( get ) and addition ( set ).

the code

var LRUCache = function (capacity) {
  this.catch = new Map()  //初始化map数据结构
  this.capacity = capacity  //容量
};

LRUCache.prototype.get = function (key) {
  if (this.catch.has(key)) {   //map中有这个元素
    let value = this.catch.get(key);  //调用map的get方法获取元素
    //更新key=>value
    this.catch.delete(key);  //删除之前的元素
    this.catch.set(key, value);  //将新获取的相同的元素以键值对推入map中

    return value   //返回关键字的值
  }
  return -1  //map中没有这个元素返回-1
};

LRUCache.prototype.put = function (key, value) {
  if (this.catch.has(key)) {  //有这个元素
    this.catch.delete(key);  //删除
  }

  //判断有没有达到存储的阈值
  if (this.catch.size >= this.capacity) {
    //移除谁 再放新值  //m.keys().next()拿到首位的键值对
    this.catch.delete(this.catch.keys().next().value)
  }
  this.catch.set(key, value);
};

//验证
let lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}

Knot

Guess you like

Origin juejin.im/post/7255876429518929975