|
| 1 | +package org.sean.array; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +public class LRUCacheRaw { |
| 6 | + static class CacheItem { |
| 7 | + int key; |
| 8 | + int value; |
| 9 | + CacheItem next; |
| 10 | + CacheItem prev; |
| 11 | + |
| 12 | + public CacheItem(int key, int value) { |
| 13 | + this.key = key; |
| 14 | + this.value = value; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + private final int capacity; |
| 19 | + private final CacheItem head; |
| 20 | + private final CacheItem tail; |
| 21 | + |
| 22 | + private final HashMap<Integer, CacheItem> itemHashMap = new HashMap<>(); |
| 23 | + |
| 24 | + public LRUCacheRaw(int capacity) { |
| 25 | + this.capacity = capacity; |
| 26 | + |
| 27 | + head = new CacheItem(-1, 0); |
| 28 | + tail = new CacheItem(10001, 0); |
| 29 | + |
| 30 | + // doubly linked list + hashMap |
| 31 | + head.prev = tail; |
| 32 | + head.next = tail; |
| 33 | + tail.next = head; |
| 34 | + tail.prev = head; |
| 35 | + } |
| 36 | + |
| 37 | + public int get(int key) { |
| 38 | + CacheItem item = itemHashMap.get(key); |
| 39 | + if (item == null) { |
| 40 | + return -1; |
| 41 | + } |
| 42 | + int val = item.value; |
| 43 | + item.prev.next = item.next; |
| 44 | + item.next.prev = item.prev; |
| 45 | + |
| 46 | + insertAfterHead(item); |
| 47 | + |
| 48 | + return val; |
| 49 | + } |
| 50 | + |
| 51 | + private void insertAfterHead(CacheItem item) { |
| 52 | + item.prev = head; |
| 53 | + item.next = head.next; |
| 54 | + head.next.prev = item; |
| 55 | + head.next = item; |
| 56 | + } |
| 57 | + |
| 58 | + public void put(int key, int value) { |
| 59 | + CacheItem item = itemHashMap.get(key); |
| 60 | + if (item == null) { |
| 61 | + if (itemHashMap.size() == capacity) { |
| 62 | + // remove the last element from the tail |
| 63 | + CacheItem prevTail = tail.prev; |
| 64 | + prevTail.prev.next = tail; |
| 65 | + tail.prev = prevTail.prev; |
| 66 | + |
| 67 | + itemHashMap.remove(prevTail.key); |
| 68 | + } |
| 69 | + item = new CacheItem(key, value); |
| 70 | + itemHashMap.put(key, item); |
| 71 | + } else { |
| 72 | + item.value = value; |
| 73 | + item.prev.next = item.next; |
| 74 | + item.next.prev = item.prev; |
| 75 | + } |
| 76 | + |
| 77 | + insertAfterHead(item); |
| 78 | + } |
| 79 | +} |
0 commit comments