import java.util.*;
public class Solution {
private Map<Integer, ListNode> map = new HashMap<>();
private ListNode head;
private ListNode tail;
private int size;
private int capacity;
public Solution(int capacity) {
// write code here
this.capacity = capacity;
this.size = 0;
}
public int get(int key) {
// write code here
if (!map.containsKey(key)) {
return -1;
}
ListNode node = map.get(key);
if (node != head) {
moveToHead(node);
}
return node.value;
}
public void set(int key, int value) {
// write code here
ListNode node = map.get(key);
if (node != null) {
node.value = value;
moveToHead(node);
} else {
node = new ListNode(key, value);
if (size == capacity) {
// remove tail
map.remove(tail.key);
tail = tail.pre;
tail.next = null;
this.size--;
}
// add to head
if (head == null) {
head = node;
tail = node;
} else {
node.next = head;
head.pre = node;
head = node;
}
map.put(key, node);
size++;
}
}
private void moveToHead(ListNode node) {
if (node == head) {
return;
}
if (node == tail) {
tail = node.pre;
tail.next = null;
} else {
ListNode pre = node.pre;
ListNode next = node.next;
pre.next = next;
next.pre = pre;
}
node.next = head;
node.pre = null;
head.pre = node;
head = node;
}
public static class ListNode {
public int key;
public int value;
public ListNode next;
public ListNode pre;
public ListNode(int key, int value) {
this.key = key;
this.value = value;
}
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution solution = new Solution(capacity);
* int output = solution.get(key);
* solution.set(key,value);
*/