一、题目地址
二、思路地址
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
};