-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU Cache.java
46 lines (39 loc) · 958 Bytes
/
LRU Cache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Node {
public int key;
public int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
class LRUCache {
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!keyToNode.containsKey(key))
return -1;
Node node = keyToNode.get(key);
cache.remove(node);
cache.add(node);
return node.value;
}
public void put(int key, int value) {
if (keyToNode.containsKey(key)) {
keyToNode.get(key).value = value;
get(key);
return;
}
if (cache.size() == capacity) {
Node lastNode = cache.iterator().next();
cache.remove(lastNode);
keyToNode.remove(lastNode.key);
}
Node node = new Node(key, value);
cache.add(node);
keyToNode.put(key, node);
}
private int capacity;
private Set<Node> cache = new LinkedHashSet<>();
private Map<Integer, Node> keyToNode = new HashMap<>();
}