-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146. LRU Cache.java
More file actions
81 lines (75 loc) · 1.88 KB
/
146. LRU Cache.java
File metadata and controls
81 lines (75 loc) · 1.88 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
public class LRUCache {
class Node {
Node next;
Node prev;
int value;
int key;
public Node (int key, int value) {
this.value = value;
this.key = key;
next = null;
prev = null;
}
}
Map<Integer, Node> map;
Node head;
Node tail;
int count;
int cap;
public LRUCache(int capacity) {
map = new HashMap<>();
head = new Node(0);
tail = new Node(0);
count = 0;
head.next = tail;
tail.prev = head;
cap = capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
Node tmp = map.get(key);
deleteNode(tmp);
insertHead(tmp);
return tmp.value;
} else {
return -1;
}
}
public void insertHead(Node node) {
Node next = head.next;
head.next = node;
node.prev = head;
next.prev = node;
node.next = next;
}
public void deleteNode(Node node) {
Node next = node.next;
node.prev.next = next;
next.prev = node.prev;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node tmp = map.get(key);
tmp.value = value;
deleteNode(tmp);
insertHead(tmp);
} else {
Node insert = new Node(key, value);
map.put(key, insert);
if (count >= cap) {
map.remove(tail.prev.key);
deleteNode(tail.prev);
insertHead(insert);
} else {
insertHead(insert);
count++;
}
}
}
}
/**
* 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);
*/