LRU缓存淘汰算法
- LRU(Least Recently Used)最近最少使用算法
- 我们程序在运行中,难免会有很多缓存,缓存可以方便我们快速获取响应的数据,但是当缓存过多时,也会占用内存空间。而LRU算法则是一种缓存优化手段,我们可以把常用的缓存保留,而不常用的缓存给清楚掉。
- 具体算法的解释大家可以查阅相关资料,我就直接上代码了,基于hashMap + 双链表实现(O1)复杂度的LRU算法
class ListNode {
val: any;
pre: IListNode = null;
next: IListNode = null;
key: any;
constructor(val: any, key = null) {
this.val = val;
this.key = key;
}
}
type IListNode = ListNode | null;
export class LRUmini {
#map: Map<any, ListNode>;
#capacity: number;
#head: IListNode = null;
#end: IListNode = null;
constructor(capacity) {
this.#capacity = capacity;
this.#map = new Map();
}
put(key, value) {
let node = this.#map.get(key);
if (node) {
node.val = value;
this.inserHeader(node);
} else {
node = new ListNode(value, key);
if (this.#map.size === 0) {
this.#head = node;
this.#end = node;
} else {
this.inserHeader(node);
}
this.#map.set(key, node);
if (this.#map.size > this.#capacity) {
this.#map.delete(this.#end!.key);
this.#end = this.#end!.pre;
this.#end!.next = null;
}
}
}
get(key) {
const node = this.#map.get(key);
if (node === undefined) {
return null;
}
this.inserHeader(node);
return node;
}
inserHeader(node) {
if (node === this.#head) return;
if (node === this.#end) {
this.#end = this.#end!.pre;
}
if (node.pre) {
node.pre.next = node.next;
}
if (node.next) {
node.next.pre = node.pre;
}
node.pre = null;
node.next = this.#head;
this.#head!.pre = node;
this.#head = node;
}
get head() {
return this.#head;
}
get end() {
return this.#end;
}
}