• lru:最近最少使用(内存淘汰策略)
      • 算法实现 ```java package com.itheima;

    import java.util.HashMap; import java.util.Map;

    public class LRUCache {

    1. Entry head, tail;
    2. int capacity;
    3. int size;
    4. Map<Integer, Entry> cache;
    5. public LRUCache(int capacity) {
    6. this.capacity = capacity;
    7. // 初始化链表
    8. initLinkedList();
    9. size = 0;
    10. cache = new HashMap<>(capacity + 2);
    11. }
    12. /**
    13. * 如果节点不存在,返回 -1.如果存在,将节点移动到头结点,并返回节点的数据。
    14. *
    15. * @param key
    16. * @return
    17. */
    18. public int get(int key) {
    19. Entry node = cache.get(key);
    20. if (node == null) {
    21. return -1;
    22. }
    23. // 存在移动节点
    24. moveToHead(node);
    25. return node.value;
    26. }
    27. /**
    28. * 将节点加入到头结点,如果容量已满,将会删除尾结点
    29. *
    30. * @param key
    31. * @param value
    32. */
    33. public void put(int key, int value) {
    34. Entry node = cache.get(key);
    35. if (node != null) {
    36. node.value = value;
    37. moveToHead(node);
    38. return;
    39. }
    40. // 不存在。先加进去,再移除尾结点
    41. // 此时容量已满 删除尾结点
    42. if (size == capacity) {
    43. Entry lastNode = tail.pre;
    44. deleteNode(lastNode);
    45. cache.remove(lastNode.key);
    46. size--;
    47. }
    48. // 加入头结点
    49. Entry newNode = new Entry();
    50. newNode.key = key;
    51. newNode.value = value;
    52. addNode(newNode);
    53. cache.put(key, newNode);
    54. size++;
    55. }
    56. private void moveToHead(Entry node) {
    57. // 首先删除原来节点的关系
    58. deleteNode(node);
    59. addNode(node);
    60. }
    61. private void addNode(Entry node) {
    62. head.next.pre = node;
    63. node.next = head.next;
    64. node.pre = head;
    65. head.next = node;
    66. }
    67. private void deleteNode(Entry node) {
    68. node.pre.next = node.next;
    69. node.next.pre = node.pre;
    70. }
    71. public static class Entry {
    72. public Entry pre;
    73. public Entry next;
    74. public int key;
    75. public int value;
    76. public Entry(int key, int value) {
    77. this.key = key;
    78. this.value = value;
    79. }
    80. public Entry() {
    81. }
    82. }
    83. private void initLinkedList() {
    84. head = new Entry();
    85. tail = new Entry();
    86. head.next = tail;
    87. tail.pre = head;
    88. }
    89. public static void main(String[] args) {
    90. LRUCache cache = new LRUCache(2);
    91. cache.put(1, 1);
    92. cache.put(2, 2); // 21
    93. System.out.println(cache.get(1)); // 12
    94. cache.put(3, 3); // 31
    95. System.out.println(cache.get(2));
    96. }

    }

    ```