运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
    实现 LRUCache 类:

    LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
    int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
    void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

    进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

    1. 输入
    2. ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
    3. [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
    4. 输出
    5. [null, null, null, 1, null, -1, null, -1, 3, 4]
    6. 解释
    7. LRUCache lRUCache = new LRUCache(2);
    8. lRUCache.put(1, 1); // 缓存是 {1=1}
    9. lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
    10. lRUCache.get(1); // 返回 1
    11. lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
    12. lRUCache.get(2); // 返回 -1 (未找到)
    13. lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
    14. lRUCache.get(1); // 返回 -1 (未找到)
    15. lRUCache.get(3); // 返回 3
    16. lRUCache.get(4); // 返回 4
    1. /**
    2. * 哈希表 + 双向链表
    3. * 时间复杂度:O(1)
    4. * 空间复杂度:O(n)
    5. */
    6. class Node {
    7. constructor(key, value) {
    8. this.key = key
    9. this.value = value
    10. this.prev = null
    11. this.next = null
    12. }
    13. }
    14. class LRUCache {
    15. constructor(capacity) {
    16. this.capacity = capacity
    17. this.map = {}
    18. // 建立默认链表
    19. this.head = new Node(null, null)
    20. this.tail = new Node(null, null)
    21. // 链表关联
    22. this.head.next = this.tail
    23. this.tail.prev = this.head
    24. }
    25. // 是否满容
    26. get isFull() {
    27. return Object.keys(this.map).length >= this.capacity
    28. }
    29. // 移除节点
    30. _remove(node) {
    31. node.prev.next = node.next
    32. node.next.prev = node.prev
    33. node.prev = null
    34. node.next = null
    35. return node
    36. }
    37. // 添加节点到头部
    38. _addHead(node) {
    39. const head = this.head.next
    40. node.next = head
    41. head.prev = node
    42. node.prev = this.head
    43. this.head.next = node
    44. }
    45. put(key, value) {
    46. // 推入已存在,更新节点
    47. if (this.map[key]) {
    48. const node = this.map[key]
    49. node.value = value
    50. this._addHead(this._remove(node))
    51. } else {
    52. // 增加新节点
    53. if (this.isFull) {
    54. // 如果容量已满,进行删除操作
    55. const node = this.tail.prev
    56. delete this.map[node.key]
    57. this._remove(node)
    58. }
    59. // 新增节点,添加到头部
    60. const node = new Node(key, value)
    61. this.map[key] = node
    62. this._addHead(node)
    63. }
    64. }
    65. get(key) {
    66. if (this.map[key]) {
    67. const node = this.map[key]
    68. this._addHead(this._remove(node))
    69. return node.value
    70. }
    71. return -1
    72. }
    73. }