技术文摘
面试官:如何用 JS 实现 LRU 缓存?
2024-12-31 01:14:15 小编
面试官:如何用 JS 实现 LRU 缓存?
在 JavaScript 中实现 LRU(Least Recently Used)缓存是一个常见的面试问题,也是实际开发中优化性能的重要手段。
LRU 缓存的核心思想是,当缓存容量达到上限时,删除最近最少使用的元素。要实现 LRU 缓存,我们可以使用双向链表和哈希表来共同完成。
创建一个节点类来表示链表中的每个元素。节点包含键、值以及指向前一个节点和后一个节点的指针。
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
接下来,创建 LRU 缓存类。在类中,我们使用一个哈希表来快速查找节点,以及一个双向链表来维护元素的访问顺序。
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = {};
this.head = new Node(null, null);
this.tail = new Node(null, null);
this.head.next = this.tail;
this.tail.prev = this.head;
}
get(key) {
if (this.cache[key]) {
this.moveToHead(this.cache[key]);
return this.cache[key].value;
}
return -1;
}
put(key, value) {
if (this.cache[key]) {
this.cache[key].value = value;
this.moveToHead(this.cache[key]);
} else {
const newNode = new Node(key, value);
this.addNode(newNode);
this.cache[key] = newNode;
if (Object.keys(this.cache).length > this.capacity) {
const removedNode = this.removeTail();
delete this.cache[removedNode.key];
}
}
}
moveToHead(node) {
this.removeNode(node);
this.addNode(node);
}
removeNode(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
addNode(node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
}
removeTail() {
const removedNode = this.tail.prev;
this.removeNode(removedNode);
return removedNode;
}
}
通过以上代码,我们成功实现了一个简单的 LRU 缓存。在实际应用中,根据具体的需求还可以对其进行进一步的优化和扩展。
理解并能够实现 LRU 缓存对于提升 JavaScript 编程能力和解决实际问题具有重要意义。希望上述实现方式能够帮助您在面对相关面试问题或实际开发场景时游刃有余。
- Python 数据可视化之箱线图的多种库绘制方法
- 那些你或许错过的现代 JavaScript 特性
- 惊!服务器遭挖矿木马入侵,CPU 飙升 200%
- Java 异常处理的十个优秀实践
- 新版 Kite:Python 之父力挺的实时代码补全工具
- 关注量子霸权的缘由及意义
- JavaScript 基础:你是否真正了解 JavaScript ?
- 阿里工程师如何破解初创公司 5 大 Java 服务困局
- Maven 可选关键字的深度图解
- Python 数据分析中必知的 TGI 指数
- Python 代码竟能预测孩子长相?人工智能的强大力量
- 7 个要点助你迅速提升数据分析水平
- 双十一开发者竟这样「作弊」,你还在手动盖楼领喵币?
- 这 3 个 Python 高级函数,你不应再忽视!
- 大数据平台常见开源工具汇总 你知晓多少