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
|
public class { private class ListNode { int key; int val; ListNode prev; ListNode next; public ListNode(int key, int val) { this.key = key; this.val = val; } }
private HashMap<Integer, ListNode> map; private int capacity; private ListNode head; private ListNode tail;
public (int capacity) { this.capacity = capacity; map = new HashMap<Integer, ListNode>(); head = new ListNode(-1, -1); tail = new ListNode(-1, -1); head.next = tail; tail.prev = head; }
public int get(int key) { if (!map.containsKey(key)) { return -1; } ListNode curt = map.get(key);
moveToTail(curt); return curt.val;
} private void moveToTail(ListNode node) {
node.prev.next = node.next; node.next.prev = node.prev; node.prev = tail.prev; node.next = tail; node.prev.next = node; tail.prev = node;
}
public void set(int key, int value) { if (get(key) != -1) { map.get(key).val = value; return; }
ListNode curt = new ListNode(key, value); if (map.size() >= capacity) { map.remove(head.next.key); head.next = head.next.next; head.next.prev = head; }
map.put(key, curt); curt.prev = tail.prev; curt.next = tail; curt.prev.next = curt; tail.prev = curt;
} }
|
近期评论