Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. class LRUCache {
  2.  
  3. private static final Node EMPTY_NODE = new Node(-1, -1);
  4.  
  5. private final int capacity;
  6. private final Map<Integer, Node> cache;
  7.  
  8. public LRUCache(int capacity) {
  9. this.capacity = capacity;
  10. this.cache = new HashMap<>(capacity);
  11. }
  12.  
  13. public int get(int key) {
  14. Node value = cache.getOrDefault(key, EMPTY_NODE);
  15. if (value != EMPTY_NODE) {
  16. merge(value);
  17. toFirst(value);
  18. }
  19.  
  20. return value.value;
  21. }
  22.  
  23. public void put(int key, int value) {
  24. Node newNode = cache.getOrDefault(key, new Node(key, value));
  25. Node actualLastNode = EMPTY_NODE.left;
  26. merge(newNode);
  27. toFirst(newNode);
  28. cache.put(newNode.key, newNode);
  29. if (cache.size() > capacity) {
  30. merge(actualLastNode);
  31. cache.remove(actualLastNode.key);
  32. }
  33. }
  34.  
  35. private void merge(Node node) {
  36. node.left.right = node.right;
  37. node.right.left = node.left;
  38. }
  39.  
  40. private void toFirst(Node node) {
  41. Node first = EMPTY_NODE.right;
  42. first.left = node;
  43. node.left = EMPTY_NODE;
  44. EMPTY_NODE.right = node;
  45. node.right = first;
  46. }
  47.  
  48. private static class Node {
  49. private int key;
  50. private int value;
  51. private Node left;
  52. private Node right;
  53.  
  54. Node(int key, int value) {
  55. this.key = key;
  56. this.value = value;
  57. this.left = this;
  58. this.right = this;
  59. }
  60.  
  61. @Override
  62. public String toString() {
  63. return "(" + this.key + ", " + this.value + ")";
  64. }
  65. }
  66. }
  67.  
  68. /**
  69. * Your LRUCache object will be instantiated and called as such:
  70. * LRUCache obj = new LRUCache(capacity);
  71. * int param_1 = obj.get(key);
  72. * obj.put(key,value);
  73. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement