leetcode 146. LRU 缓存机制(javascript)

一、题目地址

https://leetcode-cn.com/problems/lru-cache/

二、具体代码

// 时间复杂度: O(1)
// 空间复杂度: O(n)
var ListNode = function(key,value){
    this.key = key;
    this.value = value;
    this.next = null;
    this.prev = null;
}

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    //总容量
    this.capacity = capacity;
    //双向链表
    this.head = new ListNode();
    this.tail = new ListNode();
    this.head.next = this.tail;
    this.tail.prev = this.head;
    //储存键以及对应的node节点
    this.map = new Map();

};

LRUCache.prototype.insertTail = function(node) {
    this.tail.prev.next = node;
    node.prev = this.tail.prev;
    node.next = this.tail;
    this.tail.prev = node;
}

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if(!this.map.has(key)){
        return -1;
    }
    let node = this.map.get(key);
    //把最近使用过的node移到双向链表最后面
    node.prev.next = node.next;
    node.next.prev = node.prev;
    //插入链表尾部
    this.insertTail(node);

    return node.value;
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    if(this.map.has(key)){
        //获取到node
        let node = this.map.get(key);
        //修改node的val
        node.value = value;
        //移到尾部
        node.prev.next = node.next;
        node.next.prev = node.prev;
        this.insertTail(node);
    }else{
        //如果已经满了
        if(this.map.size == this.capacity){
            //删除链表最前面的节点
            let rmNode = this.head.next;
            this.head.next = this.head.next.next;
            this.head.next.prev = this.head;
            //删除map中对应的值
            this.map.delete(rmNode.key);
        }
        let node = new ListNode(key,value);
        this.map.set(key,node);
        //插入链表尾部
        this.insertTail(node);
    }
};

/**
 * 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)
 */

三、补充部分

关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值