LRU算法的JavaScript实现

75 阅读1分钟

LRU就是Least Recently Used,即最近最少使用,是一种常用的页面置换算法,将最近长时间未使用的页面淘汰,其实也很简单,就是要将不受欢迎的页面及时淘汰,不让它占着茅坑不拉shit,浪费资源。

其核心就是利用栈,进行操作,其中主要有两项操作,get和put

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

代码已通过leetcode测试

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity=capacity
    this.cache=[]
    
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    let el
    for(let i=0;i<this.cache.length;i++){
        if(this.cache[i].key===key){
            //当键值存在时,将键值移到栈顶
            var tail=this.cache.splice(i,1)
            this.cache.push(tail[0])
            
            return tail[0].val 
        }
    }

    return -1
 
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
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]=ca
                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)
        }
   
        
    }
    

/** 
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */