-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
57 lines (49 loc) · 1.29 KB
/
Copy pathLRUCache.java
File metadata and controls
57 lines (49 loc) · 1.29 KB
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
47
48
49
50
51
52
53
54
55
56
57
class LRUCache {
private final Map<Integer, Node<Integer, Integer>> map;
private final Deque<Node<Integer, Integer>> list;
private final int cap;
public LRUCache(int capacity) {
this.map = new HashMap<>(capacity);
this.list = new LinkedList<>();
this.cap = capacity;
}
public int get(int key) {
Node<Integer, Integer> t = map.get(key);
if (t == null) return -1;
refresh(t);
return t.v;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node t = map.get(key);
t.v = value;
refresh(t);
} else {
if (map.size() == cap) {
Node t = list.removeFirst();
map.remove(t.k);
}
Node t = new Node(key, value);
list.addLast(t);
map.put(key, t);
}
}
private void refresh(Node t) {
list.remove(t);
list.addLast(t);
}
private static class Node<K, V> {
K k;
V v;
Node(K k, V v) {
this.k = k;
this.v = v;
}
}
}
/**
* 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);
*/