-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
88 lines (66 loc) · 1.73 KB
/
LRUCache.java
File metadata and controls
88 lines (66 loc) · 1.73 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
package Queue;
import java.util.HashMap;
public class LRUCache {
static int capacity;
static HashMap<Integer, Node> cache;
static Node head;
static Node tail;
LRUCache(int cap) {
capacity = cap;
cache = new HashMap<>(cap);
head = null;
tail = null;
}
public static int get(int key) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
moveToFront(node);
return node.value;
}
return -1;
}
public static void set(int key, int value) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
node.value = value;
moveToFront(node);
return;
}
Node node = new Node(key, value);
if (cache.size() == capacity) {
cache.remove(tail.key);
remove(tail);
}
addToFront(node);
cache.put(key, node);
}
static void moveToFront(Node node) {
remove(node);
addToFront(node);
}
static void remove(Node node) {
Node nextNode = node.next;
Node prevNode = node.prev;
if (prevNode != null) prevNode.next = nextNode;
else head = nextNode;
if (nextNode != null) nextNode.prev = prevNode;
else tail = prevNode;
}
static void addToFront(Node node) {
node.next = head;
node.prev = null;
if (head != null) head.prev = node;
if (tail == null) tail = node;
head = node;
}
static class Node {
int key;
int value;
Node next;
Node prev;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
}