leetcode146 LRU缓存机制

/*
    put 
        if(key)
            更新节点值
            将节点移到链表的头部
        else
            if(缓存满了)
                移出最后一个节点,删除它在哈希表中的映射
            新建一个节点
            在哈希表中增加映射
            把节点加到链表头部
    get
        if(key)
            返回节点值
            将节点移到链表头部
        else
            return -1
*/
class DoubleLinkedListNode{
    constructor(key,val){
        this.key = key
        this.val = val
        this.prev = null
        this.next = null
    }
}

 class LRUCache  {
   constructor(capacity){
       this.capacity = capacity
       this.hasmap = {}
       this.dummyHead = new DoubleLinkedListNode(null,null)
       this.dummyTail = new DoubleLinkedListNode(null,null)
       this.dummyHead.next = this.dummyTail
       this.dummyTail.prev = this.dummyHead
    }
    _isFull(){
        return Object.keys(this.hasmap).length == this.capacity
    }
    _removeNode(node){
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = null
        node.next = null
        return node
    }
    _addToHead(node){
        const head = this.dummyHead.next
        node.next = head
        head.prev = node
        node.prev = this.dummyHead
        this.dummyHead.next = node
    }
    get(key){
        if(key in this.hasmap){
            const node = this.hasmap[key]
            this._addToHead(this._removeNode(node))
            return node.val
        }else{
            return -1
        }
    }
    put(key,value){
        if(key in this.hasmap){
            const node = this.hasmap[key]
            node.val = value
            this._addToHead(this._removeNode(node))
        }else{
            if(this._isFull()){
                const node = this.dummyTail.prev
                delete this.hasmap[node.key]
                this._removeNode(node)
            }
            const node = new DoubleLinkedListNode(key,value)
            this.hasmap[key] = node
            this._addToHead(node)
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值