请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
- LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
- int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
- void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
使用用map存放,方便查找,key为key,value为双向链表的节点。
使用双向链表,方便删除和添加节点。
class ListNode {constructor(key, value) {//双向链表的单个节点this.key = keythis.value = valuethis.next = null //指向后一个节点this.prev = null //指向前一个节点}}class LRUCache {constructor(capacity) {this.capacity = capacity //容量this.hashTable = {} //存放键值对信息this.count = 0 //键值对数量this.dummyHead = new ListNode() //dummy头节点 方便在链表从开始的地方插入this.dummyTail = new ListNode() //dummy尾节点 方便在链表从末尾删除this.dummyHead.next = this.dummyTail //dummyHead和dummyTail相互连接this.dummyTail.prev = this.dummyHead}get(key) {let node = this.hashTable[key]//查找哈希表中的键值对if (node == null) return -1 //不存在该键值对 返回-1this.moveToHead(node) //移动到链表头return node.value}put(key, value) {let node = this.hashTable[key] //哈希表中查找该键值对if (node == null) {let newNode = new ListNode(key, value) //不存在就创建节点this.hashTable[key] = newNode //加入哈希表this.addToHead(newNode) //加入链表头this.count++ //节点数+1if (this.count > this.capacity) { //超过容量 从队尾删除一个this.removeLRUItem()}} else {node.value = value //键值对存在于哈希表中 就更新this.moveToHead(node) //移动到队头}}moveToHead(node) {this.removeFromList(node)//从链表中删除节点this.addToHead(node)//将该节点添加到链表头}removeFromList(node) {//删除的指针操作let tempForPrev = node.prevlet tempForNext = node.nexttempForPrev.next = tempForNexttempForNext.prev = tempForPrev}addToHead(node) {//加入链表头的指针操作node.prev = this.dummyHeadnode.next = this.dummyHead.nextthis.dummyHead.next.prev = nodethis.dummyHead.next = node}removeLRUItem() {let tail = this.popTail()//从链表中删除delete this.hashTable[tail.key]//从哈希表中删除this.count--}popTail() {let tailItem = this.dummyTail.prev//通过dummyTail拿到最后一个节点 然后删除this.removeFromList(tailItem)return tailItem}}
