-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCacheM2.java
More file actions
103 lines (84 loc) · 2.51 KB
/
LRUCacheM2.java
File metadata and controls
103 lines (84 loc) · 2.51 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.HashMap;
public class LRUCacheM2 {
public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
System.out.println(cache.get(1));
cache.put(3, 3);
System.out.println(cache.get(2));
cache.put(4, 4);
System.out.println(cache.get(3));
System.out.println(cache.get(4));
}
static class LRUCache {
class DLNode {
int key;
int value;
DLNode next;
DLNode prev;
DLNode() {
}
DLNode(int key, int value) {
this.key = key;
this.value = value;
}
}
private void addNode(DLNode node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(DLNode node) {
node.next.prev = node.prev;
node.prev.next = node.next;
}
private void moveToHead(DLNode node) {
this.removeNode(node);
this.addNode(node);
}
private DLNode popTail() {
DLNode node = tail.prev;
this.removeNode(node);
return node;
}
private HashMap<Integer, DLNode> cache = new HashMap<>();
private int size;
private int capacity;
private DLNode head, tail;
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
head = new DLNode();
tail = new DLNode();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DLNode node = cache.get(key);
if (node == null) {
return -1;
}
this.moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DLNode node = cache.get(key);
if (node != null) {
node.value = value;
this.moveToHead(node);
} else {
DLNode newNode = new DLNode(key, value);
this.addNode(newNode);
cache.put(key, newNode);
this.size++;
if (this.size > this.capacity) {
DLNode tailNode = this.popTail();
cache.remove(tailNode.key);
this.size--;
}
}
}
}
}