前言:

LRU就是Least Recently Used,即最近最少使用,是一种常用的页面置换算法,将最近长时间未使用的页面淘汰,其实也很简单,就是要将不受欢迎的页面及时淘汰,不让它占着茅坑不拉shit,浪费资源。
其核心就是利用栈,进行操作,其中主要有两项操作,get和put

  1. get

get时,若栈中有值则将该值的key提到栈顶,没有时则返回null

  1. put
  • 栈未满时,若栈中有要put的key,则更新此key对应的value,并将该键值提到栈顶,若无要put的key,直接入栈
  • 栈满时,若栈中有要put的key,则更新此key对应的value,并将该键值提到栈顶;若栈中没有put的key 时,去掉栈底元素,将put的值入到栈顶

JS:

  1. var LRUCache = function(capacity) {
  2. this.capacity = capacity;
  3. this.cache = [];
  4. }
  5. LRUCache.prototype.get = function(key) {
  6. for (let i = 0; i < this.cache.length; i++) {
  7. if (this.cache[i].key === key) {
  8. let el = null;
  9. el = this.cache.splice(i, 1);
  10. this.cache.push(el[0]);
  11. return el[0].val;
  12. }
  13. }
  14. return -1;
  15. }
  16. LRUCache.prototype.put = function(key, value) {
  17. var ca = {
  18. 'key': key,
  19. 'val': value
  20. };
  21. // 当缓存中存在键值时,更新键值,并将键值放在栈顶
  22. for (let i = 0; i < this.cache.length; i++) {
  23. if (this.cache[i].key === key) {
  24. this.cache[i].val = value;
  25. let el = this.cache.splice(i, 1);
  26. this.cache.push(el[0]);
  27. return null;
  28. }
  29. }
  30. // 此时缓存中没有键值
  31. if (this.cache.length < this.capacity) {
  32. // 当缓存中未满时,直接插入
  33. this.cache.push(ca)
  34. } else {
  35. // 当缓存满时,去掉栈底元素,将新元素放在栈顶
  36. this.cache.shift();
  37. this.cache.push(ca);
  38. }
  39. }