ogv

Untitled

ogv
Oct 17th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. class LRUCache {
  2. Map<Integer, CacheItem> map;
  3. CacheItem head;
  4. CacheItem tail;
  5. int capacity;
  6.  
  7. public LRUCache(int capacity) {
  8. this.capacity = capacity;
  9. map = new HashMap<Integer, CacheItem>();
  10. head = null;
  11. tail = null;
  12. }
  13.  
  14. public int get(int key) {
  15. CacheItem item = map.get(key);
  16. if (item == null) return -1;
  17.  
  18. use(item);
  19.  
  20. return item.val;
  21. }
  22.  
  23. private void use(CacheItem item) {
  24. if (head == tail) return;
  25.  
  26. if (item.prev != null) {
  27. item.prev.linkNext(item.next);
  28. } else {
  29. head = item.next;
  30. }
  31.  
  32. tail.linkNext(item);
  33. item.next = null;
  34. }
  35.  
  36. public void put(int key, int value) {
  37. if (map.size() == capacity) {
  38. evict();
  39. }
  40. CacheItem item = new CacheItem();
  41. item.val = value;
  42. map.put(key, item);
  43.  
  44. if (tail != null ) {
  45. tail.linkNext(item);
  46. }
  47. else {
  48. head = item;
  49. tail = item;
  50. }
  51. }
  52.  
  53. private void evict() {
  54. map.remove(head.val);
  55.  
  56. if (head == tail) {
  57. head = null;
  58. tail = null;
  59. } else {
  60. head = head.next;
  61. }
  62. }
  63.  
  64. class CacheItem {
  65. public int val;
  66.  
  67. public CacheItem next;
  68.  
  69. public CacheItem prev;
  70.  
  71. public void linkNext(CacheItem n) {
  72. next = n;
  73. n.prev = this;
  74. }
  75. }
  76. }
  77.  
  78. /**
  79. * Your LRUCache object will be instantiated and called as such:
  80. * LRUCache obj = new LRUCache(capacity);
  81. * int param_1 = obj.get(key);
  82. * obj.put(key,value);
  83. */
Advertisement
Add Comment
Please, Sign In to add comment