前言:
LRU就是Least Recently Used,即最近最少使用,是一种常用的页面置换算法,将最近长时间未使用的页面淘汰,其实也很简单,就是要将不受欢迎的页面及时淘汰,不让它占着茅坑不拉shit,浪费资源。
其核心就是利用栈,进行操作,其中主要有两项操作,get和put
- get
get时,若栈中有值则将该值的key提到栈顶,没有时则返回null
- put
- 栈未满时,若栈中有要put的key,则更新此key对应的value,并将该键值提到栈顶,若无要put的key,直接入栈
- 栈满时,若栈中有要put的key,则更新此key对应的value,并将该键值提到栈顶;若栈中没有put的key 时,去掉栈底元素,将put的值入到栈顶
JS:
var LRUCache = function(capacity) {this.capacity = capacity;this.cache = [];}LRUCache.prototype.get = function(key) {for (let i = 0; i < this.cache.length; i++) {if (this.cache[i].key === key) {let el = null;el = this.cache.splice(i, 1);this.cache.push(el[0]);return el[0].val;}}return -1;}LRUCache.prototype.put = function(key, value) {var ca = {'key': key,'val': value};// 当缓存中存在键值时,更新键值,并将键值放在栈顶for (let i = 0; i < this.cache.length; i++) {if (this.cache[i].key === key) {this.cache[i].val = value;let el = this.cache.splice(i, 1);this.cache.push(el[0]);return null;}}// 此时缓存中没有键值if (this.cache.length < this.capacity) {// 当缓存中未满时,直接插入this.cache.push(ca)} else {// 当缓存满时,去掉栈底元素,将新元素放在栈顶this.cache.shift();this.cache.push(ca);}}
