-
Notifications
You must be signed in to change notification settings - Fork 0
LRU Cache
Tim_Gao edited this page Sep 16, 2016
·
1 revision
class cacheNode{
public cacheNode prev, next;
public int key, val;
public cacheNode(int k, int v){
key = k;
val = v;
}
}
public class LRUCache {
private int size = 0;
private int cap = 0;
private cacheNode head, tail;
private HashMap<Integer, cacheNode> hm;
public LRUCache(int capacity) {
cap = capacity;
hm = new HashMap<>();
}
public int get(int key) {
if(!hm.containsKey(key)){
return -1;
} else {
cacheNode crt = hm.get(key);
if(size == 1 || crt == head){
return crt.val;
}
crt.prev.next = crt.next;
if (crt!=tail){
crt.next.prev = crt.prev;
} else {
tail = crt.prev;
}
crt.next = head;
head.prev = crt;
crt.prev = null;
head = crt;
return head.val;
}
}
public void set(int key, int value) {
if(get(key) == -1){
cacheNode crt = new cacheNode(key, value);
hm.put(key, crt);
if (head == null){
head = crt;
tail = crt;
} else {
crt.next = head;
head.prev = crt;
head = crt;
}
if(size < cap){
++size;
} else {
hm.remove(tail.key);
tail = tail.prev;
tail.next = null;
}
} else {
head.val = value;
}
}
}