牛客题霸——设计LRU缓存结构(Javascript)

一、题目地址

https://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61?tpId=188&&tqId=38550&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

二、思路地址

https://www.bilibili.com/video/BV17z411B7sN/?spm_id_from=333.788.recommend_more_video.2

三、代码地址

/**
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
/* 双向链表node*/
class LinkNode {
  constructor(key, value) {
    this.key = key;
    this.val = value;
    this.front = null;
    this.next = null;
  }
}
// LRU缓存数据结构
class LRUCache {
  constructor(capacity) {
    // 容量
    this.capacity = capacity;
    // cache链表元素map
    this.map = new Map();
    // 头
    this.head = new LinkNode(0, 0);
    // 尾
    this.tail = new LinkNode(0, 0);
    // 头==next==>尾
    this.head.next = this.tail;
    // 头<==front==尾
    this.tail.front = this.head;
  }
  // 增加
  set(key, value) {
    // 如果不在map里 添加进来
    if (!this.map.has(key)) {
      // 如果已经满容量了 删除尾部最后一个节点
      if (this.capacity === this.map.size) {
        this.deleteLastNode();
      }
      const temp = this.head.next;
      const node = new LinkNode(key, value);
      node.next = temp;
      node.front = this.head;
      this.head.next = node;
      temp.front = node;
      this.map.set(key, node);
    } else {
      const node = this.map.get(key);
      node.val = value;
      this.moveNodeTopTop(node);
    }

  }
  // 获取
  get(key) {
    if (this.map.has(key)) {
      const node = this.map.get(key);
      this.moveNodeTopTop(node);
      return node.val;
    }
    return -1;
  }
  // 删除最后一个节点
  deleteLastNode() {
    const lastNode = this.tail.front;
    lastNode.front.next = this.tail;
    this.tail.front = lastNode.front;
    this.map.delete(lastNode.key);
  }
  // 把节点移动到头部变成最新的
  moveNodeTopTop(node) {
    node.front.next = node.next;
    node.next.front = node.front;
    const temp = this.head.next;
    this.head.next = node;
    node.front = this.head;
    node.next = temp;
    temp.front = node;
  }
}
function LRU(operators, k) {
  const lruCache = new LRUCache(k);
  // 存储
  const res = [];
  for (let i = 0; i < operators.length; i++) {
    const item = operators[i];
    if (item.length === 3) {
      lruCache.set(item[1], item[2]);
    } else {
      // 拿最新的
      const val = lruCache.get(item[1]);
      res.push(val);
    }
  }
  return res;
}
module.exports = {
  LRU: LRU
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值