class LRUCache {
class Node{
private Node prev;
private Node next;
private int key;
private int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private Map<Integer, Node> map;
private int capacity;
private Node head;
private Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
head = new Node(-1, -1);
tail = new Node(-1, -1);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node curt = map.get(key);
curt.next.prev = curt.prev;
curt.prev.next = curt.next;
moveLast(curt);
return map.get(key).value;
}
public void put(int key, int value) {
if (get(key) != -1) {
map.get(key).value = value;
return;
}
if (map.size() == capacity) {
Node curt = head.next;
curt.next.prev = head;
head.next = curt.next;
map.remove(curt.key);
}
Node node = new Node(key, value);
map.put(key, node);
moveLast(node);
}
private void moveLast(Node node) {
node.prev = tail.prev;
tail.prev.next = node;
node.next = tail;
tail.prev = node;
}
}
public class Memcache {
class Node{
private int value;
private int time;
public Node(int value, int time) {
this.value = value;
this.time = time;
}
}
Map<Integer, Node> map;
public Memcache() {
map = new HashMap<>();
}
public int get(int curtTime, int key) {
if (!map.containsKey(key)) return Integer.MAX_VALUE;
Node node = map.get(key);
if (node.time >= curtTime || node.time == -1) return node.value;
else return Integer.MAX_VALUE;
}
public void set(int curtTime, int key, int value, int ttl) {
int time;
if (ttl == 0) time = -1;
else time = curtTime + ttl - 1;
Node node = new Node(value, time);
map.put(key, node);
}
public void delete(int curtTime, int key) {
if (!map.containsKey(key)) return;
map.remove(key);
}
public int incr(int curtTime, int key, int delta) {
if (get(curtTime, key) == Integer.MAX_VALUE) return Integer.MAX_VALUE;
Node node = map.get(key);
node.value += delta;
return node.value;
}
public int decr(int curtTime, int key, int delta) {
if (get(curtTime, key) == Integer.MAX_VALUE) return Integer.MAX_VALUE;
Node node = map.get(key);
node.value -= delta;
return node.value;
}
}