-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path146_lru_cache.java
More file actions
92 lines (79 loc) · 2.28 KB
/
146_lru_cache.java
File metadata and controls
92 lines (79 loc) · 2.28 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
class Node {
int key;
int val;
Node prev;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
class LRUCache {
private Node start;
private Node end;
private Map<Integer, Node> dict;
private int capacity;
public LRUCache(int capacity) {
this.start = null;
this.end = null;
this.dict = new HashMap<>();
this.capacity = capacity;
}
public int get(int key) {
if (! this.dict.containsKey(key))
return -1;
/* Move the node to the end */
Node current = this.dict.get(key);
removeNode(current);
appendNode(current);
return current.val;
}
public void put(int key, int value) {
if (this.dict.containsKey(key)) {
this.dict.get(key).val = value;
removeNode(this.dict.get(key));
appendNode(this.dict.get(key));
return;
}
Node current = new Node(key, value);
this.dict.put(key, current);
appendNode(current);
if (this.dict.size() > this.capacity) {
dict.remove(this.start.key);
removeNode(this.start);
}
}
private void removeNode(Node current) {
if (this.start == current && this.end == current) {
this.start = null;
this.end = null;
} else if (this.start == current) {
this.start = current.next;
current.next.prev = null;
} else if (this.end == current) {
this.end = current.prev;
current.prev.next = null;
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
current.prev = null;
current.next = null;
}
private void appendNode(Node current) {
if (this.start == null) {
this.start = current;
this.end = current;
} else {
current.prev = this.end;
this.end.next = current;
this.end = current;
}
}
}
/**
* 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);
*/