LRU算法的JavaScript實現

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)
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章