技术文摘
面试官:如何用 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 编程能力和解决实际问题具有重要意义。希望上述实现方式能够帮助您在面对相关面试问题或实际开发场景时游刃有余。