LRU Cache

描述

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

分析

为了使查找、插入和删除都有较高的性能,这题的关键是要使用一个双向链表和一个HashMap,因为:

  • HashMap保存每个节点的地址,可以基本保证在O(1)时间内查找节点
  • 双向链表能后在O(1)时间内添加和删除节点,单链表则不行
    具体实现细节:

  • 越靠近链表头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近访问最少

  • 访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中该节点的地址
  • 插入节点时,如果cache的size达到了上限capacity,则删除尾部节点,同时要在hash表中删除对应的项;新节点插入链表头部
    LRU Cche
    Figure: LRU Cche

代码

Java中也有双向链表LinkedList, 但是 LinkedList 封装的太深,没有能在O(1)时间内删除中间某个元素的API(C++的list有个splice(), O(1), 所以本题C++可以放心使用splice()),于是我们只能自己实现一个双向链表。

本题有的人直接用 LinkedHashMap ,代码更短,但这是一种偷懒做法,面试官一定会让你自己重新实现。

  1. // LRU Cache
  2. // 时间复杂度O(logn),空间复杂度O(n)
  3. public class LRUCache {
  4. private int capacity;
  5. private final HashMap<Integer, Node> map;
  6. private Node head;
  7. private Node end;
  8. public LRUCache(int capacity) {
  9. this.capacity = capacity;
  10. map = new HashMap<>();
  11. }
  12. public int get(int key) {
  13. if(map.containsKey(key)){
  14. Node n = map.get(key);
  15. remove(n);
  16. setHead(n);
  17. return n.value;
  18. }
  19. return -1;
  20. }
  21. public void set(int key, int value) {
  22. if (map.containsKey(key)){
  23. Node old = map.get(key);
  24. old.value = value;
  25. remove(old);
  26. setHead(old);
  27. } else {
  28. Node created = new Node(key, value);
  29. if (map.size() >= capacity){
  30. map.remove(end.key);
  31. remove(end);
  32. setHead(created);
  33. } else {
  34. setHead(created);
  35. }
  36. map.put(key, created);
  37. }
  38. }
  39. private void remove(Node n){
  40. if (n.prev !=null) {
  41. n.prev.next = n.next;
  42. } else {
  43. head = n.next;
  44. }
  45. if (n.next != null) {
  46. n.next.prev = n.prev;
  47. } else {
  48. end = n.prev;
  49. }
  50. }
  51. private void setHead(Node n){
  52. n.next = head;
  53. n.prev = null;
  54. if (head!=null ) head.prev = n;
  55. head = n;
  56. if(end == null) end = head;
  57. }
  58. // doubly linked list
  59. static class Node {
  60. int key;
  61. int value;
  62. Node prev;
  63. Node next;
  64. public Node(int key, int value) {
  65. this.key = key;
  66. this.value = value;
  67. }
  68. }
  69. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/lru-cache.html