一、使用双向链表
// 双向链表class NodeList {constructor(key, value) {this.key = keythis.value = valuethis.prev = nullthis.next = null}}class LRUCache {constructor(capacity) {this.capacity = capacitythis.hasTable = {}this.count = 0this.dummyHead = new NodeList()this.dummyTail = new NodeList()this.dummyHead.next = this.dummyTailthis.dummyTail.prev = this.dummyHead}get(key) {const node = this.hasTable[key]if (node) {this.removeToHead(node)return node.value}return -1}put(key, value) {const node = this.hasTable[key]if (node) {node.value = valuethis.removeToHead(node)} else {const newNode = new NodeList(key,value)this.hasTable[key] = newNodethis.count++// 溢出则删除最后一个旧节点if (this.count > this.capacity) {this.removeOldItem()}this.addToHead(newNode)}}// 移动节点到头部removeToHead(node) {this.removeToList(node)this.addToHead(node)}// 删除节点removeToList(node) {node.prev.next = node.nextnode.next.prev = node.prev}// 节点加到头部addToHead(node) {node.next = this.dummyHead.nextthis.dummyHead.next = nodenode.prev = this.dummyHeadnode.next.prev = node}// 删除最后一个旧节点removeOldItem() {const oldItem = this.dummyTail.prevdelete this.hasTable[oldItem.key]this.count--oldItem.prev.next = this.dummyTailthis.dummyTail.prev = oldItem.prev}}
二、使用map + 迭代器
class LRUCache {constructor(capacity) {this.capacity = capacitythis.map = new Map()}get(key) {if (this.map.has(key)) {const value = this.map.get(key)this.map.delete(key)this.map.set(key, value)return value}return -1}put(key, value) {if (this.map.has(key)) {this.map.delete(key)} else {if(this.map.size >= this.capacity) {this.map.delete(this.map.keys().next().value)}}this.map.set(key, value)}}
