这里是一个JavaScript实现的LRU(最近最少使用)缓存算法:
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (this.cache.has(key)) {
// 获取值并重新插入到末尾(标记为最近使用)
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
return -1;
}
put(key, value) {
if (this.cache.has(key)) {
// 如果key已存在,删除旧的
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// 如果容量已满,删除最久未使用的(第一个)
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
// 添加新的key-value到末尾
this.cache.set(key, value);
}
}
// 使用示例
const lru = new LRUCache(3);
lru.put(1, 'a');
lru.put(2, 'b');
lru.put(3, 'c');
console.log(lru.get(1)); // 'a' - 将key 1标记为最近使用
lru.put(4, 'd'); // 容量满了,会删除最久未使用的key 2
console.log(lru.get(2)); // -1 - key 2已被删除
console.log(lru.get(1)); // 'a'
console.log(lru.get(3)); // 'c'
console.log(lru.get(4)); // 'd'
如果你需要更传统的双向链表实现方式,这里也提供一个版本:
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
// 创建虚拟头尾节点
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
}
// 添加节点到头部
addToHead(node) {
node.prev = this.head;
node.next = this.head.next;
this.head.next.prev = node;
this.head.next = node;
}
// 删除节点
removeNode(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
// 移动节点到头部
moveToHead(node) {
this.removeNode(node);
this.addToHead(node);
}
// 删除尾部节点
removeTail() {
const last = this.tail.prev;
this.removeNode(last);
return last;
}
get(key) {
const node = this.cache.get(key);
if (node) {
// 移动到头部标记为最近使用
this.moveToHead(node);
return node.value;
}
return -1;
}
put(key, value) {
const node = this.cache.get(key);
if (node) {
// 更新现有节点
node.value = value;
this.moveToHead(node);
} else {
const newNode = new Node(key, value);
if (this.cache.size >= this.capacity) {
// 删除最久未使用的节点
const tail = this.removeTail();
this.cache.delete(tail.key);
}
this.cache.set(key, newNode);
this.addToHead(newNode);
}
}
}
第一种实现利用了JavaScript Map的特性(保持插入顺序),代码更简洁。第二种是传统的双向链表实现,在某些场景下性能可能更好。两种实现的时间复杂度都是O(1)。