当前位置:   article > 正文

LRU缓存(Leetcode146)

LRU缓存(Leetcode146)
例题:

分析:

       题目要求函数get和put要达到O(1)的时间复杂度,可以用 hashMap 来实现,因为要满足逐出最久未使用的元素的一个效果,还需要配合一个双向链表来共同实现。链表中的节点为一组key-value。

我们可以用双向链表来储存数据(key-value),当调用put方法添加数据时,可以将数据(key-value)添加到双向链表的队头,队头的元素表示最新使用的元素,越靠近队尾,就是最久未用的元素。

当调用get方法时,若存在此元素,则从双向链表中把该组数据(key-value)提到队头来。

代码实现:
  1. package leetcode;
  2. import java.util.HashMap;
  3. public class LRUCacheLeetcode146 {
  4. static class LRUCache {
  5. static class Node{
  6. Node next;
  7. Node prev;
  8. int key;
  9. int value;
  10. public Node(){
  11. }
  12. public Node(int key, int value) {
  13. this.key = key;
  14. this.value = value;
  15. }
  16. }
  17. static class DoublyLinkedList{
  18. Node head;
  19. Node tail;
  20. public DoublyLinkedList() {
  21. head = tail = new Node();
  22. head.next = tail;
  23. tail.prev = head;
  24. }
  25. //头部添加 head<->1<->2<->tail 假如添加3
  26. public void addFirst(Node newNode){
  27. Node oldFirst = head.next;
  28. oldFirst.prev = newNode;
  29. head.next = newNode;
  30. newNode.prev = head;
  31. newNode.next = oldFirst;
  32. }
  33. //已知节点删除 head<->1<->2<->tail 假如删除2
  34. public void remove(Node node){
  35. Node prev = node.prev;
  36. Node next = node.next;
  37. prev.next = next;
  38. next.prev = prev;
  39. }
  40. //尾部删除
  41. public Node removeLast(){
  42. Node last = tail.prev;
  43. remove(last);
  44. return last;
  45. }
  46. }
  47. private final HashMap<Integer, Node> map = new HashMap<>();
  48. private final DoublyLinkedList list = new DoublyLinkedList();
  49. private final int capacity;
  50. public LRUCache(int capacity) {
  51. this.capacity = capacity;
  52. }
  53. public int get(int key) {
  54. if(!map.containsKey(key)){
  55. return -1;
  56. }
  57. Node node = map.get(key);
  58. //hash表中存在该数据,改组数据应放到队头
  59. //先从中删除原始数据
  60. list.remove(node);
  61. //再将改组数据添加到队头
  62. list.addFirst(node);
  63. return node.value;
  64. }
  65. public void put(int key, int value) {
  66. if(map.containsKey(key)){ //更新
  67. Node node = map.get(key);
  68. node.value = value;
  69. list.remove(node);
  70. list.addFirst(node);
  71. }else{ //添加
  72. Node newNode = new Node(key, value);
  73. map.put(key, newNode);
  74. list.addFirst(newNode);
  75. if(map.size() > capacity){
  76. Node removed = list.removeLast();
  77. //删除hash表中的数据
  78. map.remove(removed.key);
  79. }
  80. }
  81. }
  82. }
  83. public static void main(String[] args) {
  84. LRUCache cache = new LRUCache(2);
  85. cache.put(1, 1);
  86. cache.put(2, 2);
  87. System.out.println(cache.get(1)); // 1
  88. cache.put(3, 3);
  89. System.out.println(cache.get(2)); // -1
  90. cache.put(4, 4);
  91. System.out.println(cache.get(1)); // -1
  92. System.out.println(cache.get(3)); // 3
  93. }
  94. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55901
推荐阅读
相关标签
  

闽ICP备14008679号