public class LRUCache {
// double linked list
private class Node {
Node prev;
Node next;
int key;
int value;
public Node (int key, int value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
private int capacity;
private HashMap<Integer, Node> map = new HashMap<Integer, Node>();
private Node head = new Node(-1, -1);
private Node tail = new Node(-1, -1);
public LRUCache(int capacity) {
this.capacity = capacity;
tail.prev = head;
head.next = tail;
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
// delete current node from the list and move it to tail
Node curr = map.get(key);
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
moveToTail(curr);
return map.get(key).value;
}
public void put(int key, int value) {
if (get(key) != -1) {
map.get(key).value = value;
return;
}
// remove least recently used node
if (map.size() == capacity) {
map.remove(head.next.key);
head.next = head.next.next;
head.next.prev = head;
}
// insert new node to the tail
Node newNode = new Node(key, value);
map.put(key, newNode);
moveToTail(newNode);
}
public void moveToTail(Node curr) {
curr.prev = tail.prev;
tail.prev = curr;
curr.prev.next = curr;
curr.next = tail;
}
}
Leetcode 146. LRU Cache
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.