LRU
实现
- 通过组合哈希表(Hash Table)和双向链表(Doubly Linked List)实现 LRU 缓存。并且以 O(1) 的时间复杂度执行 get 和 put 操作
- 核心是对节点的新增、访问都会让节点移动到双向链表头部,当容量超过时,直接删除尾部节点即可
class LRUCache {constructor(capacity) {this.capacity = capacity;this.cache = new Map();this.head = {};this.tail = {};this.head.next = this.tail;this.tail.prev = this.head;}get(key) {const map = this.cache;if (!map.has(key)) {return -1;}const node = map.get(key);this._moveToHead(node);return node.value;}put(key, value) {const map = this.cache;if (map.has(key)) {const node = map.get(key);node.value = value;this._moveToHead(node);} else {if (map.size >= this.capacity) {const leastUsedKey = this.tail.prev.key;this._removeNode(this.tail.prev);map.delete(leastUsedKey);}const newNode = this._addNode({ key, value });map.set(key, newNode);}}_removeNode(node) {node.prev.next = node.next;node.next.prev = node.prev;}_moveToHead(node) {this._removeNode(node);this._addNode(node);}_addNode(node) {node.prev = this.head;node.next = this.head.next;this.head.next.prev = node;this.head.next = node;return node;}
}
const cache = new LRUCache(2);
cache.put(1, 10);
console.log(cache.get(1));
cache.put(2, 20);
cache.put(3, 30);
console.log(cache.get(1));