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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| package leetcode.editor.cn.mycode.ID146;
import java.util.HashMap;
public class LRUCache1 { class node{ public int val,key; public node prev,next;
public node(int key, int val) { this.key = key; this.val = val; } } class doubleList{ public node tail; public node head; private int size;
public doubleList() { this.size=0; head=new node(0,0); tail=new node(0,0); head.next=tail; tail.prev=head; }
public void addList(node x) { x.prev=tail.prev; x.next=tail; tail.prev.next=x; tail.prev=x; size++; }
public void remove(node x){ x.prev.next=x.next; x.next.prev=x.prev; size--; }
public node removeFirst(){ if(head.next==tail) { return null; } node first = head.next; remove(first); return first; }
public int size() { return size; }
}
HashMap<Integer,node> map; doubleList cache;
int cap; public LRUCache1(int capacity) { this.cap=capacity; this.map =new HashMap<>(); this.cache=new doubleList(); }
private void makeRecently(int key) { node node = map.get(key); cache.remove(node); cache.addList(node); } private void addRecently(int key ,int value) { node node = new node(key, value); cache.addList(node); map.put(key,node); } private void deleteKey(int key) { node node = map.get(key); cache.remove(node); map.remove(key); }
private void removeLeastRecently(){ node node = cache.removeFirst(); map.remove(node.key); }
public int get(int key) { if(!map.containsKey(key)) {
return -1; } makeRecently(key); return map.get(key).val;
}
public void put(int key, int value) { if(map.containsKey(key)) { deleteKey(key); addRecently(key,value); return ; } if(cap==cache.size){ removeLeastRecently(); } addRecently(key,value); }
}
|