Skip to content

Instantly share code, notes, and snippets.

@magicoder10
Created November 4, 2020 19:07
Show Gist options
  • Save magicoder10/5812475615d9d6be58b9a4e2455fdd7c to your computer and use it in GitHub Desktop.
Save magicoder10/5812475615d9d6be58b9a4e2455fdd7c to your computer and use it in GitHub Desktop.
LRU
class LRUCache {
private int capacity;
private int occupied;
private HashMap<Integer, Buffer> refs;
private Buffer head;
private Buffer tail;
public LRUCache(int capacity) {
this.capacity = capacity;
occupied = 0;
refs = new HashMap<>();
head = new Buffer();
tail = new Buffer();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!refs.containsKey(key)) {
return -1;
}
Buffer buf = refs.get(key);
remove(buf);
add(buf);
return buf.val;
}
public void put(int key, int value) {
if (refs.containsKey(key)) {
Buffer buf = refs.get(key);
buf.val = value;
remove(buf);
add(buf);
return;
}
if (occupied >= capacity) {
evict();
}
Buffer buf = new Buffer();
buf.key = key;
buf.val = value;
add(buf);
}
private void add(Buffer buf) {
buf.next = head.next;
head.next.prev = buf;
head.next = buf;
buf.prev = head;
refs.put(buf.key, buf);
occupied++;
}
private void remove(Buffer buf) {
buf.prev.next = buf.next;
buf.next.prev = buf.prev;
refs.remove(buf.key);
occupied--;
}
private void evict() {
remove(tail.prev);
}
private static class Buffer {
Buffer prev;
Buffer next;
int key;
int val;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment