1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| public class LRUCache { class Node { Node pre, next; int key, value; long expireTime;
Node(int key, int value, long expireTime) { this.key = key; this.value = value; this.expireTime = expireTime; } }
Node head = new Node(0, 0, -1); Node tail = new Node(0, 0, -1); Map<Integer, Node> map; int size;
public LRUCache(int size) { this.size = size; map = new HashMap<>(size); head.next = tail; tail.pre = head; }
public int get(int key) { int res = -1; if (map.containsKey(key)) { Node node = map.get(key); if (node.expireTime > System.currentTimeMillis()) { remove(node); insertToHead(node); res = node.value; } else { System.out.println("当前节点过期:" + key); remove(node); } } return res; }
public void put(int key, int value, long expireTime) { map.entrySet().removeIf(entry -> { boolean b = entry.getValue().expireTime <= System.currentTimeMillis(); if (b) { System.out.println("移除key:" + entry.getValue().key); } return b; } );
if (map.containsKey(key)) { Node node = map.get(key); node.value = value; remove(node); insertToHead(node); } else { int mapSize = map.size(); if (mapSize == size) { map.remove(tail.pre.key); remove(tail.pre); } Node node = new Node(key, value, expireTime); insertToHead(node); map.put(key, node); } }
public void remove(Node node) { node.pre.next = node.next; node.next.pre = node.pre; }
public void insertToHead(Node node) { Node firstNode = head.next; head.next = node; firstNode.pre = node; node.next = firstNode; node.pre = head; } }
|