-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru.java
More file actions
65 lines (58 loc) · 1.53 KB
/
Copy pathlru.java
File metadata and controls
65 lines (58 loc) · 1.53 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
import java.util.HashMap;
public class lru {
final Node head = new Node(0, 0);
final Node tail = new Node(0, 0);
final int capacity;
final HashMap<Integer, Node> map;
public lru(int capacity) {
this.capacity = capacity;
map = new HashMap(capacity);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
int res = -1;
if (map.containsKey(key)){
Node n = map.get(key);
remove(n);
insertToHead(n);
res = n.value;
}
return res;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node n = map.get(key);
remove(n);
n.value = value;
insertToHead(n);
} else{
if(map.size() == capacity){
map.remove(tail.prev.key);
remove(tail.prev);
}
Node n = new Node(key, value);
insertToHead(n);
map.put(key, n);
}
}
private void remove(Node n){
n.prev.next = n.next;
n.next.prev = n.prev;
}
private void insertToHead(Node n){
Node headNext = head.next;
head.next = n;
headNext.prev = n;
n.prev = head;
n.next = headNext;
}
class Node{
Node prev, next;
int key, value;
Node(int k, int v){
key = k;
value = v;
}
}
}