请你设计并实现一个满足 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为双向链表的节点。
    使用双向链表,方便删除和添加节点。

    1. class ListNode {
    2. constructor(key, value) {//双向链表的单个节点
    3. this.key = key
    4. this.value = value
    5. this.next = null //指向后一个节点
    6. this.prev = null //指向前一个节点
    7. }
    8. }
    9. class LRUCache {
    10. constructor(capacity) {
    11. this.capacity = capacity //容量
    12. this.hashTable = {} //存放键值对信息
    13. this.count = 0 //键值对数量
    14. this.dummyHead = new ListNode() //dummy头节点 方便在链表从开始的地方插入
    15. this.dummyTail = new ListNode() //dummy尾节点 方便在链表从末尾删除
    16. this.dummyHead.next = this.dummyTail //dummyHead和dummyTail相互连接
    17. this.dummyTail.prev = this.dummyHead
    18. }
    19. get(key) {
    20. let node = this.hashTable[key]//查找哈希表中的键值对
    21. if (node == null) return -1 //不存在该键值对 返回-1
    22. this.moveToHead(node) //移动到链表头
    23. return node.value
    24. }
    25. put(key, value) {
    26. let node = this.hashTable[key] //哈希表中查找该键值对
    27. if (node == null) {
    28. let newNode = new ListNode(key, value) //不存在就创建节点
    29. this.hashTable[key] = newNode //加入哈希表
    30. this.addToHead(newNode) //加入链表头
    31. this.count++ //节点数+1
    32. if (this.count > this.capacity) { //超过容量 从队尾删除一个
    33. this.removeLRUItem()
    34. }
    35. } else {
    36. node.value = value //键值对存在于哈希表中 就更新
    37. this.moveToHead(node) //移动到队头
    38. }
    39. }
    40. moveToHead(node) {
    41. this.removeFromList(node)//从链表中删除节点
    42. this.addToHead(node)//将该节点添加到链表头
    43. }
    44. removeFromList(node) {//删除的指针操作
    45. let tempForPrev = node.prev
    46. let tempForNext = node.next
    47. tempForPrev.next = tempForNext
    48. tempForNext.prev = tempForPrev
    49. }
    50. addToHead(node) {//加入链表头的指针操作
    51. node.prev = this.dummyHead
    52. node.next = this.dummyHead.next
    53. this.dummyHead.next.prev = node
    54. this.dummyHead.next = node
    55. }
    56. removeLRUItem() {
    57. let tail = this.popTail()//从链表中删除
    58. delete this.hashTable[tail.key]//从哈希表中删除
    59. this.count--
    60. }
    61. popTail() {
    62. let tailItem = this.dummyTail.prev//通过dummyTail拿到最后一个节点 然后删除
    63. this.removeFromList(tailItem)
    64. return tailItem
    65. }
    66. }