forked from sherxon/AlgoDS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU.java
More file actions
81 lines (68 loc) · 1.59 KB
/
Copy pathLRU.java
File metadata and controls
81 lines (68 loc) · 1.59 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package codeforces;
import java.util.HashMap;
import java.util.Map;
/**
* Why Did you create this class? what does it do?
*/
public class LRU {
public static void main(String[] args) {
LRU lru = new LRU(10);
lru.put(10, 13);
}
int cap = 0;
Map<Integer, Integer> map;
Node root, tail;
Map<Integer, Node> mm = new HashMap<>();
public LRU(int capacity) {
cap = capacity;
map = new HashMap<>();
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
Node n = mm.get(key);
if (n.next == null) {
return map.get(key);
}
n.val = n.next.val;
if (n.next == tail) {
n.next = null;
tail = n;
} else {
n.next = n.next.next;
}
tail.next = new Node(key);
tail = tail.next;
mm.put(key, tail);
return map.get(key);
}
public void put(int key, int value) {
Node n;
int ex = get(key);
if (ex == -1) {
n = new Node(key);
if (root == null && tail == null)
root = tail = n;
else
tail.next = n;
tail = n;
} else {
n = tail;
}
map.put(key, value);
mm.put(key, n);
if (map.size() > cap) {
map.remove(root.val);
mm.remove(root.val);
root = root.next;
}
}
class Node {
int val;
Node next;
Node(int val) {
this.val = val;
}
}
}